我想创建一个HTML5画布,允许用户涂鸦。类似于这个图片:
之后,我想获取所涂鸦区域的坐标(也就是X,Y和X2,Y2)。如何实现这一功能?
mousedown
和mousemove
上将您绘制的点注册到数组中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)
};
让我们来看看主要的辅助方法。您需要纠正鼠标位置,以下是一种方法:
function getXY(e) {
var rect = canvas.getBoundingClientRect();
return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
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);
}
要检查区域是否与涂鸦的文字重叠,只需使用交集测试:
假设区域被存储为对象或字面对象,即:
var rect = {left: minX, top: minY, right: maxX, bottom: maxY};
然后将这两个对象传递给此类函数:
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}