canvas自适应宽高

文章发布于 2023-05-06

利用宽高百分比让canvas自适应。自适应的几个关键因素如下

  • html父标签有设置宽高
  • canvas style属性设置宽高为100%

实现canvas自适应的思路是,canvas 按照设计图尺寸画图,然后给canvas标签上的style属性添加宽高百分百**style="width:100%;height:100%"**。canvas会自适应父标签的尺寸,经过调整父标签来实现自适应。

案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas自适应高级应用</title>
    <style>
        * {
            margin: 0;padding: 0;
        }
        #canvas {
            width: 1000px;
            height: 500px;
        }
    </style>
</head>
<body>
    <div id="canvas"></div>
    <script type="text/javascript">
        const root = document.getElementById('canvas')
        //创建canvas
        const canvas = document.createElement('canvas')
        canvas.width = 1300
        canvas.height = 600
        canvas.style.width = '100%'
        canvas.style.height = '100%'
        
        const ctx = canvas.getContext('2d')
        ctx.fillStyle="#ff0000"
        ctx.fillRect(0,0,1300,600)

        // 绘制一条线
        ctx.beginPath()
        ctx.strokeStyle = '#fff'
        ctx.lineWidth = 3
        ctx.moveTo(650,0)
        ctx.lineTo(650,600)
        ctx.stroke()
        ctx.restore()
        // 绘制线条
        
        // ctx.scale(2,1)

        ctx.lineWidth = 5
        ctx.strokeRect(100,100,250,150)

        root.append(canvas)
        
    </script>
</body>
</html>

上面实例中,创建了一个父标签div。并给父标签设置1000*500px的尺寸,div标签里面创建了一个canvas画布,画布大小1300 * 600px。通过给canvas设置宽高实现自适应div之后,canvas会缩放到1000 * 500px。如果让canvas自适应,只需要设置div的大小即可。canvas自适应案例的完整代码已上传,仓库地址https://gitee.com/usuing/lession/tree/master/canvas自适应高级应用

自适应之前

1300*6001300*600

自适应之后

自适应之后变小了。画布里面的矩形和线条偏移量保持一致。