在HTML5画布上绘制并获取坐标

4
我想创建一个HTML5画布,允许用户涂鸦。类似于这个图片: http://theclosetentrepreneur.com/wp-content/uploads/2010/06/Free-Form-Circle.jpg 之后,我想获取所涂鸦区域的坐标(也就是X,Y和X2,Y2)。如何实现这一功能?

在点击事件中,您已经获得了坐标,但我不记得它们是本地的还是全局的 - 我曾经用jcrop做过类似的事情。 - Mr.TK
1个回答

5
要从您绘制的区域中获取一个区域,可以执行以下操作:
  • mousedownmousemove上将您绘制的点注册到数组中
  • 在鼠标松开时运行最小-最大例程以获取总面积。
这很容易实现。

此处有一个实时演示

在演示中,只需在一个单词周围绘制区域。在鼠标松开时,该区域将用正方形突出显示。
示例代码执行以下操作:
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);
}

另一种技术是在文本中心点处检查该点是否在矩形内(如果有多个点,则可以用它来排除多选文本等情况)。
希望这能帮到您!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接