JSFiddle - React, Tailwind, and code Playground
by Laia
HTML
<canvas id="myCanvas" width="400" height="400"></canvas>
JavaScript
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
var xTopFromLine = []; // we need to store all the x coordinate where the lines start from the top in an array.
//emptyLine
function emptyLine( xTop){
context.beginPath();
context.moveTo(xTop, 0);
context.lineTo(250, 400);
context.lineWidth = 1;
}
//singleLine
function drawSingleLine( xTop, color){
emptyLine( xTop);
context.strokeStyle = color;
context.stroke();
}
function drawAllLinesIncanvas() {
for(i=90; i<410 ;i+=15){
var xTop = i,
color = '#28B9A2'; // we set the default color to green
if (xTop >= 200 && xTop <= 300) { // If the lines are in the middle of the canvas, we set the color to yellow
color = '#AECD49';
}
drawSingleLine( xTop, color);
xTopFromLine.push([xTop]); // we store each xTop coordinate of every line in the array
}
}
//we draw all the lines in the canvas:
drawAllLinesIncanvas();
//event mousehover
canvas.addEventListener("mousemove", function(e){
for(i=0; i<xTopFromLine.length; i++){ // we iterate over all the coordinates stored from every line
var x = e.pageX,
y = e.pageY;
emptyLine(xTopFromLine[i]);
if (context.isPointInStroke(x, y)) { // if the mouse hover over the empty line with the same exact coordinates of ecah colored line
drawSingleLine(xTopFromLine[i], 'blue'); // we draw a new line with a new color in the same position of the previous line
}
}
});