JSFiddle - React, Tailwind, and code Playground

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

HTML

<div class='wrapper' style='background-image: url(http://wyrta.com/wp-content/uploads/2015/07/background-blue-500x500.png)'>
  <canvas id='canvas' width='500' height='500'></canvas>
</div>

CSS

body {
  background: #f0f;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

.wrapper {
  background: #fff center no-repeat;
  background-size: cover;
}

#canvas {
  background: transparent;
}

JavaScript

const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')

// CONFIG
const brushSize = 20
  
let brushMode = true
let isDrawing = false
let isClearing = false

// EVENTS
canvas.onkeypress = (e) => console.log(e)
canvas.onkeyup = (e) => isClearing = false

canvas.onmousedown = (e) => isDrawing = true
canvas.onmouseup = (e) => isDrawing = false
canvas.onmouseout = (e) => isDrawing = false

canvas.onmousemove = (e) => {
console.log(isClearing)
	if (!isDrawing) return false

  const [x, y] = [e.offsetX, e.offsetY]
  
	ctx.beginPath()
  
  if (isClearing) {
   	ctx.globalCompositeOperation = 'destination-out'
  }
  
  ctx.arc(x, y, brushSize, 0, 2*Math.PI);
  ctx.fill();
}