我有discussion表示如何制作铅笔工具。
如何使用铅笔工具检测鼠标是否悬停在绘制区域/点/图像上?然后,它将通过在其上创建一个圆圈来突出显示起点和终点。
答案 0 :(得分:3)
在你的情况下,唯一的解决方案是将所有绘制的点保存到数组中,它们本身保存在一个包含所有修补程序的数组中:
onmousedown
:创建一个新的路径数组。onmousemove
:
var ctx = canvas.getContext("2d"),
painting = false,
lineThickness = 1;
canvas.width = canvas.height = 600;
var dCanvas = canvas.cloneNode(true);
dCtx = dCanvas.getContext('2d');
pCanvas = canvas.cloneNode(true);
pCtx = pCanvas.getContext('2d');
dCtx.fillStyle = "#FFF";
pCtx.fillStyle = "red";
ctx.fillRect(0, 0, 600, 600);
var pathes = [],
currentPath;
canvas.onmousedown = function(e) {
currentPath = [];
pathes.push(currentPath);
painting = true;
};
canvas.onmouseup = function(e) {
painting = false;
}
canvas.onmousemove = function(e) {
pCtx.clearRect(0, 0, canvas.width, canvas.height);
var mouseX = e.pageX - this.offsetLeft,
mouseY = e.pageY - this.offsetTop;
if (painting) {
var lastPoint = currentPath[currentPath.length-1] || {
x: e.pageX - canvas.offsetLeft,
y: e.pageY - canvas.offsetTop
};
var x1 = mouseX,
x2 = lastPoint.x,
y1 = mouseY,
y2 = lastPoint.y;
var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
if (steep) {
var x = x1;
x1 = y1;
y1 = x;
var y = y2;
y2 = x2;
x2 = y;
}
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;
var y = y1;
y1 = y2;
y2 = y;
}
var dx = x2 - x1,
dy = Math.abs(y2 - y1),
error = 0,
de = dy / dx,
yStep = -1,
y = y1;
if (y1 < y2) {
yStep = 1;
}
lineThickness = 5-Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) / 10;
if (lineThickness < 1) {
lineThickness = 1;
}
for (var x = x1; x < x2; x++) {
if (steep) {
dCtx.fillRect(y, x, lineThickness, lineThickness);
currentPath.push({x: y,y: x});
} else {
dCtx.fillRect(x, y, lineThickness, lineThickness);
currentPath.push({x: x,y: y});
}
error += de;
if (error >= 0.5) {
y += yStep;
error -= 1.0;
}
}
currentPath.push({x: mouseX,y: mouseY});
} else {
pathes.forEach(function(path) {
if (path.some(function(point) {
return isBetween(mouseX, point.x, 5) && isBetween(mouseY, point.y, 5)
})) {
pCtx.beginPath();
pCtx.arc(path[0].x+2.5, path[0].y+2.5, 5, 0, Math.PI*2);
pCtx.fill();
pCtx.beginPath();
pCtx.arc(path[path.length-1].x+2.5, path[path.length-1].y+2.5, 5, 0, Math.PI*2);
pCtx.fill();
}
});
}
ctx.fillRect(0, 0, 600, 600);
ctx.drawImage(dCanvas, 0, 0);
ctx.drawImage(pCanvas, 0, 0);
}
function isBetween(x, y, z) {
return (x >= y - z && x <= y + z);
}
&#13;
canvas {
border: 1px solid
}
&#13;
<canvas id="canvas" width="500" height="500"></canvas>
&#13;
答案 1 :(得分:2)
您可以从画布中获取(每像素)图像数据:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData。然后检查鼠标是否悬停在绿色像素上。