Created
February 26, 2020 01:22
-
-
Save Nithanaroy/3677cdde61893e3731b3f882ad7745d1 to your computer and use it in GitHub Desktop.
Lets users draw on the browser using their pointer device
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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