gpt4 book ai didi

javascript - Canvas 宽度值不正确

转载 作者:行者123 更新时间:2023-11-30 09:53:04 25 4
gpt4 key购买 nike

所以我认为代码

<!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();">使脚本在页面加载时运行,此时 Canvas 尚未捕获修改后的值(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>

现在我想象脚本在 Canvas 从嵌入样式中获取属性后运行,我将看到 600。不正确。我仍然得到 300,即使 Canvas 适本地具有宽度 = 600。发生了什么事?

最佳答案

Default width of canvas is 300 x 150 [Ref]. Canvas does not consider css defined with. Either you defined width/heigh attributes or assign those values as properties of canvas element.

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>

关于javascript - Canvas 宽度值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35331128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com