Danni Danni - 1 month ago 9
HTML Question

how to get mouseover to draw on html canvas with event listener with my code? https://jsfiddle.net/dannixx/d0p0j8cL/

how to get mouseover to draw on html canvas with event listener with my code? https://jsfiddle.net/dannixx/d0p0j8cL/
jifiddle file, i want to be able to draw line on canvas with mouseover https://jsfiddle.net/dannixx/d0p0j8cL/

<!DOCTYPE html>
<html>

<head>
<title>Canvas</title>
<style type="text/css">
#Canvas1 {

border: : dotted 3px black;
background-color: blue;


}

</style>

<script>

window.onload = function(){

var theCanvas = document.getElementById("Canvas1");

if (theCanvas && document.getContext("2d")){
var ctx = theCanvas.getContext("2d";)
if(ctx){
ctx.fillStyle = "lightblue";
ctx.fillRect(0,0 ctx.canvas.width, ctx.canvas.height)


}


}
}




</script>
</head>

<body>
<h1>cnavas</h1>
<p>ex</p>
<canvas id="Canvas1" width="400", height="300"></canvas>





<p id="demo"></p>


</body>

</html>

Answer

Here is a really simple example using a onmousemove listener that updates the new mouse coordinates and draws a line from the previous coordinates to the new coordinates. Run it and see!

   var x = null;
   var y = null;
   var c = null;
   var ctx = null;


function getPos(e) {
         //if it is the first time the event listener is called then set x and y to the new mouse coordinate
         if(x == null) {
             x=e.clientX;
             y=e.clientY;
           }
         //otherwise draw from the previous point (x, y) to the new coordinates (e.clientX, e.clientY).

         ctx.beginPath();
         ctx.moveTo(x,y);
         ctx.lineTo(e.clientX,e.clientY);
         ctx.stroke();
         x=e.clientX;
         y=e.clientY;
    	}
     
 
      window.onload = function(){
       c=document.getElementById("Canvas1");
       ctx=c.getContext("2d");
    }
<canvas onmousemove="getPos(event)" id="Canvas1" width="400", height="300"></canvas>