16

I'm trying to draw a grid on a <canvas> element with the ultimate goal of making a Go board.

For some reason the grid is looking stretched, with the lines being thicker than 1 pixel and the spacing being completely wrong. It doesn't even start in the (10,10) position..

It would be great if someone could take a look at tell me what I'm doing wrong.

http://jsfiddle.net/h2yJn/

alt text

Acorn
  • 49,061
  • 27
  • 133
  • 172
  • Found the answer here http://stackoverflow.com/questions/2588181/canvas-is-stretch-when-using-css-but-normal-with-old-width-and-height-propert and here http://stackoverflow.com/questions/2892041/how-to-avoid-html-canvas-auto-stretching – Acorn Nov 13 '10 at 12:22
  • This https://codereview.stackexchange.com/a/135207/210612 may help too – Carson Jul 15 '21 at 12:11

2 Answers2

36

I've found the problem. I was setting the dimensions of the <canvas> using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.

var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');

http://jsfiddle.net/h2yJn/66/

alt text

Acorn
  • 49,061
  • 27
  • 133
  • 172
1

Please try it outside jsfiddle, maybe jsfiddle is applying some linear transformation.

Also please make sure that you add 0.5 everywhere to both x and y coordinates. Alternatively, you can apply translate(0.5, 0.5) to shift all coordinates by half a pixel.

pts
  • 80,836
  • 20
  • 110
  • 183
  • I'm getting the same result on jsbin.com, I'm pretty sure I've added 0.5px everywhere I could possibly add it. That wouldn't cause such dramatic effects anyway though would it? – Acorn Nov 13 '10 at 11:33
  • 1
    Another way is just to start a cycle from 0.5 like this: `for (var i = 0.5; i < fieldSize+1; i+=40) {...` – Aleksandr Kravets Jan 13 '15 at 10:30