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

标签 javascript html canvas html5-canvas

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

相关文章:

javascript - 滞后的字符串搜索,如何改进?

javascript - 在 Vue.js 中将 Prop 传递给根实例

javascript - 在从初始点移动的滚动固定元素上

php - 如何在固定容器中添加滚动条

android - 如何让 Jsoup 获取 URL 的桌面版本

javascript - 将纯文本数据转换为json

javascript - 如何将当前系统日期与另一个日期进行比较

javascript - 使用箭头绑定(bind)在 Canvas 上定位 Div

c# - Silverlight - 在用户控制范围内公开 Canvas

javascript - 如何在页面上附加和运行 JavaScript/jQuery 动画