为什么以下代码不调整画布大小?该ID是正确的。
var canvas;
canvas = document.getElementById('myCanvas');
canvas.width = 1000;
canvas.height = 500;
但是,这有效:
var canvas
canvas = document.createElement('canvas');
canvas.width = 1000;
canvas.height = 500;
为什么创建新的画布有效,但按ID获取已制成的画布却不起作用?
HTML Canvas就像这样:
<canvas id="myCanvas" width="0" height="0"></canvas>
最佳答案
您正在做的事情应该没问题-只要确保将canvas
添加到DOM后,您的脚本即可运行。您应该检查控制台是否有其他错误。
这是一个例子:
HTML:
<canvas id="myCanvas" width="0" height="0"></canvas>
<script>
var canvas;
canvas = document.getElementById('myCanvas');
alert(canvas.width + " , " + canvas.height);
canvas.width = 1000;
canvas.height = 500;
alert(canvas.width + " , " + canvas.height);
</script>
JS Fiddle here