move canvas element to mouse

Solutions on MaxInterview for move canvas element to mouse by the best coders in the world

showing results for - "move canvas element to mouse"
Julia
19 Oct 2016
1<!DOCTYPE HTML>
2<html>
3  <head>
4    <style>
5      body {
6        margin: 0px;
7        padding: 0px;
8      }
9    </style>
10  </head>
11  <body>
12    <canvas id="myCanvas" width="578" height="200"></canvas>
13    <script>
14      function writeMessage(canvas, message) {
15        var context = canvas.getContext('2d');
16        context.clearRect(0, 0, canvas.width, canvas.height);
17        context.font = '18pt Calibri';
18        context.fillStyle = 'black';
19        context.fillText(message, 10, 25);
20      }
21      function getMousePos(canvas, evt) {
22        var rect = canvas.getBoundingClientRect();
23        return {
24          x: evt.clientX - rect.left,
25          y: evt.clientY - rect.top
26        };
27      }
28      var canvas = document.getElementById('myCanvas');
29      var context = canvas.getContext('2d');
30
31      canvas.addEventListener('mousemove', function(evt) {
32        var mousePos = getMousePos(canvas, evt);
33        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
34        writeMessage(canvas, message);
35      }, false);
36    </script>
37  </body>
38</html>
39