Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Me or jsfiddle bug?

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?

like image 283
Daniel Gruszczyk Avatar asked Jan 26 '26 21:01

Daniel Gruszczyk


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!