1

I am trying to draw on a html5 canvas and the following code should give me a diagonal line from left top to right bottom. However I do not get the expected result. is there any transformation required to the context ? HTML

<canvas id="myCanvas" style="margin-left:auto; margin-right:
     auto;width:700px;height:100px;border:1px solid grey">
</canvas> 

JS

var canvas = $("#myCanvas");
var pen = canvas[0].getContext("2d");    
pen.strokeStyle = "#000000"; pen.lineWidth = "2";    
pen.beginPath(); pen.moveTo(700, 100); pen.lineTo(0,0);
pen.stroke();

http://jsfiddle.net/neilghosh/DvjAP/2/

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Neil
  • 5,919
  • 15
  • 58
  • 85
  • I found an workaround at http://stackoverflow.com/questions/4397315/html5-canvas-distorted but still not sure why CSS doesn't work. – Neil Mar 29 '12 at 10:39

1 Answers1

4

jsFiddle demo

Strange but true. The Canvas element W/H have (not only*) to be set inline like:

 <canvas id="myCanvas" width="700" height="100"></canvas>

Put the rest in your CSS stylesheet:

    #myCanvas{
        margin-left:auto;
        margin-right: auto;  
        border:1px solid grey
    }
  • For a better understanding:
    Canvas element W/H values are: 300x150 by default, but if you change that values in your stylesheet that will actually stretch your canvas renderings like it would do for any other image.

  • Another way to change your W/H is with JS like:

    canvas[0].width = 700;
    canvas[0].height = 100;

Demo

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 1
    Slight amend: width and height values shouldn’t have `px` suffixes. Dimension values in HTML5 are either pixel values without a suffix or percent values with a `%` suffix. – Robin Whittleton Mar 29 '12 at 11:59
  • @Robin That's true! It might be a fast-typing(non-thinking) error! Thanks for mentioning! Updated. – Roko C. Buljan Mar 29 '12 at 12:01