Skip to content

Instantly share code, notes, and snippets.

@Nithanaroy
Created February 26, 2020 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nithanaroy/3677cdde61893e3731b3f882ad7745d1 to your computer and use it in GitHub Desktop.
Save Nithanaroy/3677cdde61893e3731b3f882ad7745d1 to your computer and use it in GitHub Desktop.
Lets users draw on the browser using their pointer device
const c = document.getElementById("myCanvas");
c.addEventListener("mousedown", setLastCoords); // fires before mouse left btn is released
c.addEventListener("mousemove", freeForm);
const ctx = c.getContext("2d");
function setLastCoords(e) {
const {x, y} = c.getBoundingClientRect();
lastX = e.clientX - x;
lastY = e.clientY - y;
}
function freeForm(e) {
if (e.buttons !== 1) return; // left button is not pushed yet
penTool(e);
}
function penTool(e) {
const {x, y} = c.getBoundingClientRect();
const newX = e.clientX - x;
const newY = e.clientY - y;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.moveTo(lastX, lastY);
ctx.lineTo(newX, newY);
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.closePath();
lastX = newX;
lastY = newY;
}
let lastX = 0;
let lastY = 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment