gpt4 book ai didi

javascript - 使用 JS 创建与嵌入 HTML 时,HTML Canvas 坐标不同

转载 作者:太空狗 更新时间:2023-10-29 16:35:49 28 4
gpt4 key购买 nike

使用 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.

Source

像这样它会很好地工作:

        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/

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