【问题标题】:Incorrect canvas width value画布宽度值不正确
【发布时间】:2022-02-22 13:12:56
【问题描述】:

所以我认为代码

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>Log Canvas Width</title>
    <style>
        #canvas {
            background: #888888;
            width: 600px;
            height: 600px;
        }
    </style>
    <script>
        function draw() {
            var canvas = document.getElementById('canvas'),
                         context = canvas.getContext('2d');
            document.write(canvas.width);
        }
    </script>
</head>
<body onload="draw();">
        <canvas id='canvas'>
            Canvas not supported
        </canvas>
</body>
</html>

打印 300 而不是 600,因为 &lt;body onload="draw();"&gt; 使脚本在页面加载时运行,而此时画布尚未捕获修改后的值 (600)。

然后我将代码修改为:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>Log Canvas Width</title>
    <style>
        #canvas {
            background: #888888;
            width: 600px;
            height: 600px;
        }
    </style>
</head>
<body>
    <canvas id='canvas'>
        Canvas not supported
    </canvas>
    <script type="text/javascript">
        var canvas = document.getElementById('canvas'),
                     context = canvas.getContext('2d');
        document.write(canvas.width);
    </script>
</body>
</html>

现在我想象脚本在画布从嵌入样式中获取属性之后运行,我将看到 600。不正确。即使画布的 width = 600,我仍然得到 300。发生了什么?

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    画布的默认宽度是300 x 150 [Ref]。 Canvas 不考虑使用定义的css。您定义了width/heigh 属性,或者将这些值分配为propertiescanvas 元素。

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    alert(canvas.width);
    <canvas id='canvas' width='600'>
      Canvas not supported
    </canvas>

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    canvas.width = 600;
    alert(canvas.width);
    <canvas id='canvas'>
      Canvas not supported
    </canvas>

    【讨论】:

      【解决方案2】:

      canvas.widthcanvas.style.width 是两个不同的东西。在大多数情况下,它们应该相等,但它们也可以不同以实现各种效果。你得到的 300 是画布默认宽度。

      canvas.width 是画布内实际可用的像素数,而canvas.style.width 是 HTML 元素的宽度,因此如果两个数字不同,您可以看到拉伸、像素化等。


      以下是一些更详细地描述该问题的答案:

      【讨论】:

      • 啊,它们可以通过 canvas.style 访问......谢谢!我读过(当然,忘记了)关于 CSS 不会影响某事或其他的内容。这没有意义。现在我正在收集 canvas.width 指定 logical 宽度,而 CSS 指定浏览器中的实际大小。然而,实际的扫描线渲染发生在画布上。它只是缩放以适应 CSS 尺寸。听起来我现在明白了吗?
      • 完全正确!抱歉,我忘了提到 canvas.style 实际上代表 CSS 样式,无论它是如何设置以及在何处设置。
      【解决方案3】:

      我发现将画布的宽度和高度设置为等于样式的宽度和高度有助于我稍后进行计算。 喜欢:

      canvas.width = canvas.getBoundingClientRect().width;
      canvas.height = canvas.getBoundingClientRect().height;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        相关资源
        最近更新 更多