Skip to content Skip to sidebar Skip to footer

Change Color Lines In Canvas When Mouseover

I have some lines in canvas. I want each single line change color when the mouseover that line but I have some issues with this problem. Is there any JS library to help me solve th

Solution 1:

First you need to store the paths of all the lines in an array.

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

After that you can create an empty line in the exact position of each of your colored lines, like this:

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

And check if your mouse is over the "ghost line" you have just created.

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

  }

});

You can check the jsFiddle I created (I did some refactorizations): https://jsfiddle.net/laia89/6wtLper3/


Post a Comment for "Change Color Lines In Canvas When Mouseover"