Reputation: 1
I am trying to get HTML 5 canvas for my application work as a drawing board. The problem I am facing is:
The drawing is happening at some offset from the mouse pointer. I am using the Jquery .offset
method to calculate the offset of the event on the canvas. One other weird thing I notice is that though the width of the canvas tag is 150px, a line drawn from (0,10) to (150,10) reaches just mid-way of the canvas area and even a line as big as (0,10) to (250,10) is also visible. Isn't the "pixels" calculated from the event object map directly to Canvas tag's "point co-ordinates" ? What else can be wrong here? Sample code:
if (event.pageX || event.pageY)
{
event._x = event.pageX;
event._y = event.pageY;
}
else if (event.clientX || event.clientY)
{
event._x = event.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
event._y = event.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
var canvasElem = $('#' + canvasId);
canvasOffset = canvasElem.offset();
event._x -= Math.floor(canvasOffset.left);
event._y -= Math.floor(canvasOffset.top);
////////////// CODE STRIPPED //////////////////////////////
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
// This function is called every time you move the mouse. Obviously, it only
// draws if the tool.started state is set to true (when you are holding down
// the mouse button).
this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
// This is called when you release the mouse button.
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
}
}
Found the Problem:
I was using a string to set the Height and Width of the Canvas. Something Like: canvas.height = "200px";
But rather we should always use numbers to set the height/width for canvas like. canvas.height = 200;
That solves the problem.
Upvotes: 0
Views: 162
Reputation: 69683
You can get the coordinates of the upper-left corner of your canvas by using the jQuery .offset() function. Subtract these from the coordinates delivered by the mouse event, and you have the position on the canvas.
Regarding the scaling issues you experience, There are two possible explanations:
A: you use translate, transform or scale to change the coordinate system of the canvas (but when you would do that, you would certainly be aware of it)
B: you are using CSS style properties to change the size of the canvas. The resolution of a canvas is determined by the width
and height
properties of the <canvas>
HTML tag. When you use CSS to change the width or height with which the canvas is rendered, it is first drawn in the internal resolution, and then scaled accordingly for display in the browser.
Upvotes: 1