JSFiddle - React, Tailwind, and code Playground

by Yining Shi

HTML

<canvas width=256 height=256 id="canvas_hover"></canvas>
<canvas width=256 height=256 id="canvas_draw"></canvas>

CSS

canvas{border:1px solid;}

JavaScript

var drawOnSecond = false;

function start(){
    var canvas_hover_tmp = document.getElementById('canvas_hover');
    canvas_hover = canvas_hover_tmp.getContext('2d');
    var canvas_click_tmp = document.getElementById('canvas_draw');
    canvas_click = canvas_click_tmp.getContext('2d');
    
    window.addEventListener('mousemove', moved, false); //move square with mouse on mouse move
    window.addEventListener('mousedown', draw, false); //draw square to canvas at specific location from where mouse is
    window.addEventListener('mousedown', enableDraw, false); // enable drawing while moving the mouse
    window.addEventListener('mouseup', disableDraw, false); // disable
}
function moved(pos){    
    canvas_hover.clearRect(0,0,1000,600);
    var x = pos.clientX;
    var y = pos.clientY;
    canvas_hover.fillRect(x-25, y-25,50,50);
    if(drawOnSecond)
        draw(pos);
}

function enableDraw(){
    drawOnSecond = true;
}

function disableDraw(){
    drawOnSecond = false;
}

function draw(draw_pos){
    var x = draw_pos.clientX;
    var y = draw_pos.clientY;
    canvas_hover.fillRect(x-25,y-25,50,50);
}
window.addEventListener('load', start, false); //call first function start