我想创建一个允许用户涂鸦的HTML5画布。
与此图片类似:
之后,我想要潦草地区的坐标(即X,Y和X2,Y2)。
我该怎么做?
答案 0 :(得分:3)
要从您绘制的区域获取区域,您可以执行以下操作:
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};
然后将其中两个对象传递给函数like this:
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
另一种技巧是在文本的中心有一个点并检查该点是否在矩形内(如果有多个点则可以使用它来排除多选文本等等。) / p>
希望这有帮助!