Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML canvas coordinates are different when created using JS versus embed in HTML

Playing with HTML5 canvas and JS, I found a strange behaviour when a canvas is added to the HTML body directly versus creating a canvas using 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>

Please see the code & ouput here

I expected the line (stroke) to be a consistent diagonal across the canvas but alas!. Please help me know where am I going wrong!

Note: I forgot to mention, I tried this on Chrome only not sure if the behaviour is consistent for other browsers.

like image 991
Sriram Avatar asked May 22 '15 13:05

Sriram


1 Answers

So, basically if you change from style to attribute it works.

Why ?

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

Like this it will work fine:

        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>
like image 72
Joel Almeida Avatar answered Oct 12 '22 22:10

Joel Almeida