Created
July 24, 2020 02:10
-
-
Save avrebarra/75dbfedd1f8d1d77a9e7cfd288535c46 to your computer and use it in GitHub Desktop.
extract coordinate sequences of canvas-drawn line
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='utf-8'> | |
<meta http-equiv='X-UA-Compatible' content='IE=edge'> | |
<title>Coordinates from Line - results shown in log</title> | |
<meta name='viewport' content='width=device-width, initial-scale=1'> | |
<script src='./index.js'></script> | |
</head> | |
<body> | |
</body> | |
</html> |
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
function distance(a, b) { | |
return Math.sqrt(((b.x - a.x) ^ 2) + ((b.y - a.y) ^ 2)) | |
} | |
document.addEventListener("DOMContentLoaded", function () { | |
// setup things | |
// create canvas element and append it to document body | |
var canvas = document.createElement('canvas'); | |
document.body.appendChild(canvas); | |
document.body.style.margin = 0; | |
canvas.style.position = 'fixed'; | |
var ctx = canvas.getContext('2d'); | |
var resizeCanvas = () => { | |
ctx.canvas.width = window.innerWidth; | |
ctx.canvas.height = window.innerHeight; | |
} | |
window.addEventListener('resize', resizeCanvas); | |
resizeCanvas(); | |
// start drawer | |
var cursor = { x: 0, y: 0 }; | |
var points = [] | |
document.addEventListener('mousemove', updateCanvas); | |
document.addEventListener('mousedown', updateCursor); | |
document.addEventListener('mouseenter', updateCursor); | |
document.addEventListener('mouseup', finalize); | |
// new position from mouse event | |
function updateCursor(e) { | |
cursor.x = e.clientX; | |
cursor.y = e.clientY; | |
} | |
function updateCanvas(e) { | |
// mouse left button must be pressed | |
if (e.buttons !== 1) return; | |
ctx.beginPath(); // begin | |
ctx.lineWidth = 5; | |
ctx.lineCap = 'round'; | |
ctx.strokeStyle = '#c0392b'; | |
ctx.moveTo(cursor.x, cursor.y); // from | |
updateCursor(e); | |
ctx.lineTo(cursor.x, cursor.y); // to | |
// push to queue | |
if (!points.length || distance(cursor, points[points.length - 1]) > 3) { | |
points.push({ x: cursor.x, y: cursor.y }) | |
} | |
ctx.stroke(); | |
} | |
// finalize draw | |
function finalize(e) { | |
// add last point | |
points.push({ x: cursor.x, y: cursor.y }) | |
// show and clean canvas | |
console.log('points', points); | |
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); | |
points = [] | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment