gpt4 book ai didi

jquery - 在 HTML5 Canvas 上绘制并获取坐标

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:30 25 4
gpt4 key购买 nike

我想创建一个允许用户涂鸦的 HTML5 Canvas 。

类似于这张图片:

http://theclosetentrepreneur.com/wp-content/uploads/2010/06/Free-Form-Circle.jpg

之后,我想要涂鸦区域的坐标(即 X,Y 和 X2,Y2)。

我该怎么做?

最佳答案

要从您绘制的区域中获取区域,您可以执行以下操作:

  • mousedownmousemove 上用数组注册您绘制的点
  • 在鼠标上移时运行最小-最大例程以获得总面积。

这实现起来相当简单。

A live demo here

在演示中,只需在其中一个单词周围绘制区域。鼠标悬停时,该区域会以正方形突出显示。

示例代码执行以下操作:

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);
}

另一种技术是在文本的中心放置一个点,然后检查该点是否在您的矩形内(如果有多个点,则您可以使用它来排除多选文本等)。

希望这对您有所帮助!

关于jquery - 在 HTML5 Canvas 上绘制并获取坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22542021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com