画布宽度值不正确

时间:2016-02-11 05:01:55

标签: javascript html5 canvas

所以我认为代码

<!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)。

然后我将代码修改为:

<!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.发生了什么?

2 个答案:

答案 0 :(得分:1)

  

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

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

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

答案 1 :(得分:1)

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

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

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