HTML5 Game - Canvas Event Mouse input

Description

Mouse input

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html lang = "en">
<head>
  <style type = "text/css">
  #drawing{//from   w w  w  . j ava  2  s  . c  o m
    position: absolute;
    left: 100px;
    top: 100px;
  }
  </style>
  <script type = "text/javascript">
    let drawing;
    let con;
    let startX = 10;
    let startY = 10;
    let endX = 100;
    let endY = 100;
    let OFF_X = 100;
    let OFF_Y = 100;

    function init(){
      drawing = document.getElementById("drawing");
      con = drawing.getContext("2d");

      con.strokeStyle = "red";
      con.lineWidth = 5;

      document.onmousedown = getCoords;
      setInterval(draw, 100);
    }

    function getCoords(e){
      //pageX and pageY are page position compensate for position of canvas
      endX = e.pageX - OFF_X;
      endY = e.pageY - OFF_Y;
    }
    function draw(){
      //clear screen
      con.clearRect(0, 0, 200, 200);
      con.strokeStyle = "black";
      con.strokeRect(0, 0, 200, 200);
      
      con.strokeStyle = "red";
      con.beginPath();
      con.moveTo(startX, startY);
      con.lineTo(endX, endY);
      con.stroke();
      con.closePath();

    }
  </script>
</head>

<body onload = "init()">
  <h1>Mouse Input Demo</h1>

  <canvas id = "drawing"
          height = "200"
          width = "200">
    <p>Canvas not supported</p>
  </canvas>



</body>
</html>

Related Topic