JSFiddle - React, Tailwind, and code Playground

by Константин Дралюк

HTML

<canvas class="canC" id="canV" width=500 height=600></canvas>

CSS

body {    background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAlUlEQVRYR+2WsQ0EIQwEbXpAopbrAZESUhQ1AAkBXVEDAb6jBRP8B0s+yJpklnvvstYizRMRyjmTtVaD096buNYqzjnVB3NOaq3RGEPFhxBwAAzAAAzAAAz8gYFSijCzqmYH+ngyxqj4k3N+nkduep5Sops9wV+T5abnMUa62RM4AAZgAAZgAAZ+b8B7Lzc9PzW82RMvg0g+JLdy9xIAAAAASUVORK5CYII=');


    background-size: 32px 32px;
    background-repeat: repeat;
}
.canC { width:500px;  height:600px;}

JavaScript

var canvas = document.getElementById('canV')
var ctx = canvas.getContext('2d')
var mouse = {
    x: 0,
    y: 0,
    isDrawing: 0,
}

function mouseMove(e) {
    mouse.x = e.offsetX || e.clientX
    mouse.y = e.offsetY || e.clientY
    if (e.type === 'mousedown') {
        mouse.isDrawing = true
    } else if (e.type === 'mouseup' || e.type === 'mouseout') {
        mouse.isDrawing = false
    }
}

canvas.addEventListener('mousemove', mouseMove)
canvas.addEventListener('mousedown', mouseMove)
canvas.addEventListener('mouseup', mouseMove)
canvas.addEventListener('mouseout', mouseMove)
canvas.addEventListener('mouseover', mouseMove)

var pointer = document.createElement('canvas')
pointer.width = canvas.width
pointer.height = canvas.height
pointer.ctx = pointer.getContext('2d')
pointer.ctx.lineCap = 'round'
pointer.ctx.lineJoin = 'round'
pointer.ctx.lineWidth = 50

ctx.globalAlpha = 1

function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    if (mouse.isDrawing) {
        if (!mouse.lastx) {
            mouse.lastx = mouse.x
            mouse.lasty = mouse.y
            pointer.ctx.strokeStyle = '#f00'
            ctx.globalAlpha = 0.6
        }
      
        pointer.ctx.beginPath()
        pointer.ctx.moveTo(mouse.lastx, mouse.lasty)
        pointer.ctx.lineTo(mouse.x, mouse.y)
        pointer.ctx.stroke()
        mouse.lastx = mouse.x
        mouse.lasty = mouse.y
    } else {
        mouse.lastx = null
        ctx.fillStyle = '#f00'
        ctx.globalAlpha = 0.6 
        ctx.beginPath()
        ctx.arc(mouse.x, mouse.y, pointer.ctx.lineWidth / 2, 0, Math.PI * 2)
        ctx.fill()
    }

    ctx.drawImage(pointer, 0, 0)
    requestAnimationFrame(update) 
}
update()