本文介绍了画布宽度值不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我认为代码

<!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因为< body onload =draw() ;> 使脚本在页面加载时运行,此时画布尚未捕获修订后的值(600)。

prints 300 rather than 600 because <body onload="draw();"> makes the script run at page loading, and at that time the canvas has not yet caught the revised value (600).

但后来我将代码修改为:

But then I modify the code to:

<!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.不是这样。我仍然得到300,即使画布正好宽度= 600.发生了什么?

Now I'm imagining that the script runs after the canvas has taken the attribute from the embedded style and that I will see 600. Not true. I still get 300, even though the canvas duly has width = 600. What is happening?

推荐答案

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

canvas.width and canvas.style.width are two different things. In most of the cases, they should be equal, but they can also be different for achieving various effects. 300 you're getting is the canvas default width.

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

canvas.width is the actual number of pixels that are available inside the canvas, while canvas.style.width is the width of the HTML element, thus you can see stretching, pixelation, etc, if the two numbers are different.

以下是一些答案,更详细地描述了这个问题:

Here are a couple of answers that describe the issue in more detail:





  • https://stackoverflow.com/a/28142612/965907
  • https://stackoverflow.com/a/34539170/965907
  • https://stackoverflow.com/a/28879318/965907

这篇关于画布宽度值不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:48