use*_*252 4 html jquery html5-canvas
我想创建一个允许用户涂鸦的 HTML5 画布。
类似于此图像:

之后,我想要涂鸦区域的坐标(即 X,Y 和 X2,Y2)。
我该怎么做?
小智 5
要从您绘制的区域中获取区域,您可以执行以下操作:
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)
};
Run Code Online (Sandbox Code Playgroud)
让我们看看主要的辅助方法。您需要更正鼠标位置,这是一种方法:
function getXY(e) {
var rect = canvas.getBoundingClientRect();
return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
Run Code Online (Sandbox Code Playgroud)
然后计算最小值和最大值,简单地遍历您存储和调整的点:
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);
}
Run Code Online (Sandbox Code Playgroud)
要检查区域是否与潦草的单词重叠,只需使用交集测试:
假设区域存储为对象或文字对象,即:
var rect = {left: minX, top: minY, right: maxX, bottom: maxY};
Run Code Online (Sandbox Code Playgroud)
然后传递两个这些对象的功能的这样的:
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
Run Code Online (Sandbox Code Playgroud)
另一种技术是在文本中心放置一个点并检查该点是否在您的矩形内(如果有多个点,那么您可以使用它来排除多选文本等)。
希望这可以帮助!