使用JS而不是嵌入HTML创建时,HTML画布坐标是不同的

时间:2015-05-22 13:00:11

标签: javascript html 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>

请参阅代码&amp; ouput here

我预计画线(笔画)在画布上是一致的对角线但是唉!请帮我知道我哪里出错!

注意:我忘了提及,我在Chrome上尝试过此操作,但不确定其他浏览器的行为是否一致。

2 个答案:

答案 0 :(得分:2)

所以,基本上如果你从一个样式改为另一个属性就可以了。

为什么?

  

宽度和高度属性似乎决定了画布坐标系的宽度或高度,而CSS属性只决定了它将在其中显示的框的大小。

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>

答案 1 :(得分:0)

Canvas webservicewidth属性与其CSS heightwidth不同。设置height属性决定了总可绘制像素区域,可以(但不是必须)使用CSS缩放到屏幕上更大或更小。

正常场景:使canvas属性边界大于CSS边界

事实上,要制作高密度显示画布,必须将canvas.width/heightcanvas.width设置为css的两倍。换句话说,你可能会这样做:

canvas.height

正常场景:使画布属性边界小于CSS边界

另一方面,为了使一些应用程序像游戏快,canvas.width和canvas.height可能被限制为// Two canvas pixels per screen pixel so it looks nice // on a high density (in this case pixel ratio: 2) display canvas.width = 800; canvas.height = 800; canvas.style.width = '400px'; canvas.style.height = '400px'; (或小的东西),然后用CSS缩放以占据整个屏幕。由于画布上处理的像素总数很少,因此游戏将比使用非常大的画布并填充屏幕更快。显然游戏看起来会有所不同,因为CSS会缩放图形(无论好坏)。