Sri*_*ram 5 html javascript html5 canvas html5-canvas
使用HTML5画布和JS时,我发现在将画布直接添加到HTML主体而不是使用JS创建画布时会出现奇怪的行为.
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="test" width="200" height="200" style="border:1px solid #000000;">
</canvas>
<script>
var c=document.getElementById("test");
ctx=c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
// creating canvas using JS
c = document.createElement("canvas");
c.id="MyCanvas";
c.style.width="200px";
c.style.height="200px";
c.style.border="1px solid #000000";
ctx=c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
document.body.appendChild(c);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
请在此处查看代码和输出
我期望画线(笔画)在画布上是一致的对角线但是唉!请帮我知道我哪里错了!
注意:我忘了提及,我在Chrome上试过这个,但不确定其他浏览器的行为是否一致.
所以,基本上,如果你从样式更改为属性,它就会起作用。
为什么 ?
看起来 width 和 height 属性决定了画布坐标系的宽度或高度,而 CSS 属性只决定了显示它的框的大小。
像这样它会正常工作:
var c = document.getElementById("test");
ctx = c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(200, 200);
ctx.stroke();
// creating canvas using JS
c = document.createElement("canvas");
c.id = "MyCanvas";
c.setAttribute("width", "200px")
c.setAttribute("height", "200px")
c.style.border = "1px solid #000000";
ctx = c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(200, 200);
ctx.stroke();
document.body.appendChild(c);Run Code Online (Sandbox Code Playgroud)
<canvas id="test" width="200" height="200" style="border:1px solid #000000;"></canvas>Run Code Online (Sandbox Code Playgroud)