JSFiddle - React, Tailwind, and code Playground

by Darker

HTML

<canvas width="300" height="300" id="x"></canvas>

Coordinates: <input type="text" id="coords" />

CSS

canvas {
    
  border: 1px solid black;
}

JavaScript

HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();
  //Recalculate mouse offsets to relative offsets
  x = event.clientX - rect.x;
  y = event.clientY - rect.y;
  //Debug
  console.log("x(",x,") = event.clientX(",event.clientX,") - rect.x(",rect.x,")");
  //Return as array
  return [x,y];
}


var last = [0,0];

var coords = document.getElementById("coords");
document.getElementById("x").addEventListener("mousemove", function(event) {
    var curent = this.relativeCoords(event);
    coords.value = curent.join(" x ");
    //Draw
    var ctx = this.getContext("2d");
    ctx.lineWidth = 3;
    ctx.strokeStyle = "rgb("+
            Math.round(Math.random()*255)+","+
            Math.round(Math.random()*255)+","+
            Math.round(Math.random()*255)+")";
    ctx.lineCap="round";
    ctx.beginPath();
    ctx.moveTo(last[0], last[1]);
    ctx.lineTo(curent[0],curent[1]);
    ctx.stroke();   
    last = curent;
});