Reputation: 53
I noticed a weird issue while tried to draw a line with canvas. I have a simple script which save the point when you click first (this will be the start point for path) and when you click again and the first point is already saved, it saves the end point. So i have a start and an end point for path, this is OK. After this I using the .moveTo(), .lineTo() and .stroke() functions to draw a line. And here apears the problem: the X coordinates always going to be 1.4 times more and the Y coordinates 0.8 times less then the original coordinates (both starting and ending points). I have no idea what causes this issue. I'm tracing the variables and they working fine, the .moveTo() and .lineTo() functions getting the right coordinates, but they drawing that transformed line.
Here is a pice of my code:
var points = [null, null];
var canvas = $('canvas#myid');
var ctx = canvas[0].getContext("2d");
var end = false;
$(canvas).click(function(event) {
if ( null == points[0] ) {
// First click - first coordinates
points[0] = [event.pageX, event.pageY];
} else if ( null == points[1] && null != points[0] ) {
// Second click - second coordinates
points[1] = [event.pageX, event.pageY];
ctx.fillStyle = "black";
ctx.moveTo(points[0][0], points[0][1]);
ctx.lineTo(points[1][0], points[1][1]);
ctx.stroke();
end = true;
} else if ( null != points[0] && null != points[1] ) end = true;
if ( true === end ) {
points = [null, null];
}
}
I have no idea, hope you guys could help me, thanks!
Upvotes: 2
Views: 938
Reputation: 5146
You forgot to close parenthesis at the end of your code );
and there is no need to use $(canvas).
you should use it like canvas.
jsFiddle Live Demo
$(function()
{
var points = [null, null];
var canvas = $('canvas#myid');
var ctx = canvas[0].getContext("2d");
var end = false;
canvas.click(function(event)
{
if ( null == points[0] )
{
// First click - first coordinates
points[0] = [event.pageX, event.pageY];
}
else if ( null == points[1] && null != points[0] )
{
// Second click - second coordinates
points[1] = [event.pageX, event.pageY];
ctx.fillStyle = "black";
ctx.moveTo(points[0][0], points[0][1]);
ctx.lineTo(points[1][0], points[1][1]);
ctx.stroke();
end = true;
}
else if ( null != points[0] && null != points[1] )
{
end = true;
}
if ( true === end )
{
points = [null, null];
}
}); // Here you missed
});
Upvotes: 1