gpt4 book ai didi

javascript - 鼠标悬停时更改 Canvas 中的颜色线

转载 作者:行者123 更新时间:2023-11-28 00:52:31 24 4
gpt4 key购买 nike

我在 Canvas 上有一些线条。当鼠标悬停在该行上时,我希望每一行都改变颜色,但我对此问题有一些疑问。

有没有什么JS库可以帮我解决这个问题?

你能帮帮我吗?谢谢

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

var width = 400;
var height = 400;

for(i=0; i<120 ;i+=15){
context.beginPath();
context.moveTo(90+i, 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = '#28B9A2';
context.stroke();
}

for(i=0; i<120 ;i+=15){
context.beginPath();
context.moveTo(300+i, 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = '#28B9A2';
context.stroke();
}

//blue
for(i=0; i<100 ;i+=15){
context.beginPath();
context.moveTo(200+i, 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = '#AECD49';
context.stroke();
}

function detectLine(x, y) {
console.log(x, y);
var imageData = context.getImageData(0, 0, width, height),
inputData = imageData.data,
pData = (~~x + (~~y * width)) * 4;
if (inputData[pData + 3]) {
return true;
context.strokeStyle = '#28B9A2';
}

return false;
}

canvas.addEventListener("mousemove", function(e){
var x = e.pageX,
y = e.pageY;
detectLine(x, y);
});

最佳答案

首先,您需要将所有行的路径存储在一个数组中。

var xTopFromLine = [];

for(i=0; i<120 ;i+=15){
var xTop = 90+i;
context.beginPath();
context.moveTo(xTop , 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = '#28B9A2';
context.stroke();

xTopFromLine.push([xTop]);
}

for(i=0; i<120 ;i+=15){
var xTop = 300+i;
context.beginPath();
context.moveTo(xTop , 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = '#28B9A2';
context.stroke();

xTopFromLine.push([xTop]);
}

//blue
for(i=0; i<100 ;i+=15){
var xTop = 200+i;
context.beginPath();
context.moveTo(xTop , 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = '#AECD49';
context.stroke();

xTopFromLine.push([xTop]);
}

之后,您可以在每条彩色线条的确切位置创建一个空行,如下所示:

//emptyLine
function emptyLine( xTop){
context.beginPath();
context.moveTo(xTop, 0);
context.lineTo(250, 400);
context.lineWidth = 1;
}
//single colored Line
function drawSingleLine( xTop, color){
context.beginPath();
context.moveTo(xTop, 0);
context.lineTo(250, 400);
context.lineWidth = 1;
context.strokeStyle = color;
context.stroke();
}

然后检查您的鼠标是否在您刚刚创建的“幻影线”上。

canvas.addEventListener("mousemove", function(e){

for(i=0; i<xTopFromLine.length; i++){
var x = e.pageX,
y = e.pageY;

emptyLine(xTopFromLine[i]);
if (context.isPointInStroke(x, y)) {
drawSingleLine(xTopFromLine[i], 'blue');
}

}

});

您可以查看我创建的 jsFiddle(我做了一些重构):https://jsfiddle.net/laia89/6wtLper3/

关于javascript - 鼠标悬停时更改 Canvas 中的颜色线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46543611/

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