3

Simple canvas drawing, seems like on jsFiddle coordinates are not being recognized correctly:
JS:

var w = $(".trace").width();
var h = $(".trace").height();

var bgCanvas = $("<canvas></canvas>").addClass("canvas");
bgCanvas.width(w).height(h);
var bgContext = bgCanvas[0].getContext("2d");

$(".trace").append(bgCanvas);

bgContext.strokeStyle = "#000";
bgContext.moveTo(0,0);
//this line should go to the middle of the canvas
//instead it goes much further both horizontally and vertically
bgContext.lineTo(200,100);
bgContext.stroke();

HTML:

<div class="trace"></div>

CSS:

.trace{
    width: 400px;
    height: 200px;
    background: yellow;
}
.canvas{
    border: 1px #000 dotted;
}

jsFiddle

Checked on latest IE and Chrome.
They (jsFiddle developers) suggest to share and check with others before submitting an issue on github, so there... Is it my mistake somwhere, or is it jsFiddle?

Daniel Gruszczyk
  • 5,379
  • 8
  • 47
  • 86
  • 1
    [Canvas is stretched when using CSS but normal with “width” / “height” properties](http://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties), [canvas width attribute](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width) – Andreas Dec 17 '13 at 13:40

1 Answers1

1

Change this line:

bgCanvas.width(w).height(h);

to this and it will work:

bgCanvas.attr({width: w, height:h});

By using .width and .height you are simply modifying the CSS size of the canvas element not its bitmap. As the default size is 300 x 150 just just gets stretched to whatever you set with CSS.

Modified fiddle

  • now this is odd... so it is jQuery then? for canvas we can't simply use $.width(), but instead go via attributes? Thanks. – Daniel Gruszczyk Dec 17 '13 at 13:41
  • @DanielGruszczyk not really jQuery's fault, it is setting the CSS dimension as expected but for canvas you need to explicitly set its width and height *attributes* which is not the same as the CSS equivalents. –  Dec 17 '13 at 13:43
  • yes, Andreas just posted a link in comments to my original post, describing the issue – Daniel Gruszczyk Dec 17 '13 at 13:45
  • @DanielGruszczyk In addition I [write a bit about setting canvas size here](http://abdiassoftware.com/blog/2013/11/how-to-properly-set-size-of-the-canvas-element/). –  Dec 17 '13 at 13:46