Reputation: 399
I want to create a HTML5 canvas that allows user to scribble.
Similar to this image:
After that, I want the coordinates of the scribbled area (i.e. X,Y and X2,Y2).
How do I go about doing that?
Upvotes: 4
Views: 3996
Reputation:
To get a region from the area you draw you can do:
mousedown
and mousemove
This is fairly simple to implement.
In the demo simply draw the area around one of the words. On mouse up the area is highlighted with a square.
The example code does the following:
var points = [], // point array, reset for each mouse down
isDown = false, // are we drawing?
last; // for drawing a line between last and current point
canvas.onmousedown = function(e) {
var pos = getXY(e); // correct mouse position
last = pos; // set last point = current as it is the first
points = []; // clear point array (or store previous points)
isDown = true; // pen is down
points.push(pos); // store first point
bg(); // helper method to redraw background
};
canvas.onmousemove = function(e) {
if (!isDown) return; // if pen isn't down do nothing..
var pos = getXY(e); // correct mouse position
points.push(pos); // add point to array
ctx.beginPath(); // draw some line
ctx.moveTo(last.x, last.y);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
last = pos; // update last position for next move
};
canvas.onmouseup = function(e) {
if (!isDown) return;
isDown = false;
minMax(); // helper to calc min/max (for demo)
};
Lets see the main helper methods. You need to correct the mouse positions, this is one way to do it:
function getXY(e) {
var rect = canvas.getBoundingClientRect();
return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
Then to calculate min and max values simple iterate over the points you have stored and adjust:
function minMax() {
var minX = 1000000, // set to something out of range of canvas
minY = 1000000,
maxX = -1000000,
maxY = -1000000,
i = 0, p; // iterator and point
for(; p = points[i++];) {
if (p.x > maxX) maxX = p.x;
if (p.y > maxY) maxY = p.y;
if (p.x < minX) minX = p.x;
if (p.y < minY) minY = p.y;
}
// now we have min and max values, use them for something:
ctx.strokeRect(minX, minY, maxX - minX, maxY - minY);
}
To check if the region overlaps the scribbled words just use intersection test:
Assuming regions are stored as object or literal object, ie:
var rect = {left: minX, top: minY, right: maxX, bottom: maxY};
then pass two of those objects to a function like this:
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
Another technique is to have a point in the center of the text and check if that point is inside your rectangle (if more than one point is then you can use that to rule out multi-selected texts and so forth).
Hope this helps!
Upvotes: 5