Canvas Draw

Free drawing on Canvas

by gnijuohz

HTML

<input type="button" id="clear" value="Clear Canvas"/>
<canvas id="myCanvas" width="500" height="500"></canvas>

CSS

#myCanvas {
  border: 1px solid #222;
}

JavaScript

let canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

var flag = false,
    prevX = 0,
    currX = 0,
    prevY = 0,
    currY = 0;

var x = "black",
    y = 2;

let w = canvas.width;
let h = canvas.height;

// idea from: http://stackoverflow.com/a/8398189/1062364
canvas.addEventListener("mousemove", function (e) {
   findxy('move', e)
 }, false);
canvas.addEventListener("mousedown", function (e) {
  findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
  findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
  findxy('out', e)
}, false);
        
function draw() {
  ctx.beginPath();
  ctx.moveTo(prevX, prevY);
  ctx.lineTo(currX, currY);
  ctx.strokeStyle = x;
  ctx.lineWidth = y;
  ctx.stroke();
  ctx.closePath();
}

function findxy(res, e) {
  if (res == 'down') {
    prevX = currX;
    prevY = currY;
    currX = e.clientX - canvas.offsetLeft;
    currY = e.clientY - canvas.offsetTop;

    flag = true;
    ctx.beginPath();
    ctx.fillStyle = x;
    ctx.fillRect(currX, currY, 2, 2);
    ctx.closePath();
  }
  if (res == 'up' || res == "out") {
    flag = false;
  }
  if (res == 'move') {
    if (flag) {
      prevX = currX;
      prevY = currY;
      currX = e.clientX - canvas.offsetLeft;
      currY = e.clientY - canvas.offsetTop;
      draw();
    }
  }
}

function clearCanvas() {
	 ctx.clearRect(0, 0, w, h);
}

let clearButton = document.getElementById('clear');
clearButton.onclick = clearCanvas;