The idea is to redraw the background when a line is moved along a canvas:
my working code is the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="xmouse">xmouse</p>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
document.addEventListener('mousemove', readXMouse); //Mouse move inside the graph
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var mouseXold =0;
var imgData;
//Draw a diagonal line
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 25;
ctx.moveTo(0, 0);
ctx.lineTo(300, 140);
ctx.stroke();
ctx.closePath();
function readXMouse(e){
var mouseXdet = `${e.clientX}`-10
if(mouseXdet>300){return}
document.getElementById("xmouse").innerHTML=mouseXdet;
if(imgData != undefined){ctx.putImageData(imgData,mouseXold-1,0)}//Restore the background
imgData = ctx.getImageData(mouseXdet-1, 0,1 ,150) //memorize the background
//Draw vertical line
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.lineWidth = 1;
ctx.moveTo(mouseXdet, 0);
ctx.lineTo(mouseXdet, 150);
ctx.stroke();
ctx.closePath();
mouseXold=mouseXdet //Stores old x value
}
</script>
</body>
</html>
My question is: why I can't store only the line but I need to store and restore from mouseXdet-1 to mouseXdet-1+2 to not having picture mess up like in the second picture?