JSFiddle - React, Tailwind, and code Playground

by Vitaliy

HTML

<canvas id="can" >
        </canvas>

CSS

canvas{
                width: 200px;
                height: 200px;
                border: solid;
            }

JavaScript

var old_x = -1;
var old_y = -1;
 
function draw(xPos,yPos){
	var cvs = document.getElementById("can");
  var ctx = cvs.getContext("2d");
	var rect = cvs.getBoundingClientRect();
	var x = xPos// - rect.left;
  var y = yPos// - rect.top;
	if (old_x == -1 || old_y == -1){
		old_x = x;
    old_y = y;
	}
	ctx.beginPath();
  ctx.moveTo(old_x, old_y);
  ctx.lineTo(x, y);
  ctx.stroke();
 	old_x = x;
  old_y = y;
}
 
function reset(){
	old_x = -1;
  old_y = -1;
  pressed = false;
}
            
var c = document.getElementById('can');
var pressed = false;
c.onmousedown = function(e){
	console.log(e);
	draw(e.clientX, e.clientY);
  pressed = true;
}
c.onmouseup = reset;
c.onmousemove = function(e){
	if(pressed){
  	draw(e.clientX, e.clientY);
  }
}