使用 HTML5 canvas 和 JS,当直接将 Canvas 添加到 HTML 正文而不是使用 JS 创建 Canvas 时,我发现了一种奇怪的行为。
<!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>
请查看代码和输出 here
我希望线条(描边)在 Canvas 上是一条一致的对 Angular 线,但唉!请帮助我知道我哪里出错了!
注意:我忘了说,我只是在 Chrome 上试过这个,但不确定其他浏览器的行为是否一致。
最佳答案
所以,基本上,如果您从样式更改为属性,它就会起作用。
为什么?
It seems that the width and height attributes determine the width or height of the canvas's coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown.
像这样它会很好地工作:
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);
<canvas id="test" width="200" height="200" style="border:1px solid #000000;"></canvas>
关于javascript - 使用 JS 创建与嵌入 HTML 时,HTML Canvas 坐标不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30397395/