Skip to content

Instantly share code, notes, and snippets.

@benbotto
Last active April 13, 2020 15:00
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 benbotto/66ba4c28f0be9382c3fc22cd40e63df4 to your computer and use it in GitHub Desktop.
Save benbotto/66ba4c28f0be9382c3fc22cd40e63df4 to your computer and use it in GitHub Desktop.
Draw a Line in a Canvas
(function(window, gl) {
'use strict';
// The canvas element and a 2D rendering context.
const easel = document.getElementById('easel');
const ctx = easel.getContext('2d');
// This point (vec2) holds the first point in the drawing. Transformations
// happen about this point.
let startPoint = null;
// This is used as a rendering queue, and points (vec2) are added to it when
// the mouse is moved and the primary mouse button is down. Points are
// dequeued as they're rendered.
const pointQueue = [];
// On mousedown the drawing starts.
easel.addEventListener('mousedown', e => {
// Only draw if the main button is down.
if (e.buttons !== 1)
return;
// Reset any transforms and clear the canvas.
ctx.resetTransform();
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// Track the start point.
startPoint = gl.vec2
.fromValues(e.offsetX, e.offsetY);
// Start the point queue fresh with just the start point.
pointQueue.splice(0, pointQueue.length);
pointQueue.push(startPoint);
});
// Draw a line from the last point to the current point.
easel.addEventListener('mousemove', e => {
if (e.buttons !== 1)
return;
// Add the point to the rendering queue.
pointQueue.push(gl.vec2.fromValues(e.offsetX, e.offsetY));
// Render in an animation frame.
window.requestAnimationFrame(render);
});
// Main rendering logic that renders all the points in the queue.
function render() {
ctx.beginPath();
ctx.lineWidth = 2;
while (pointQueue.length > 1) {
const lastPoint = pointQueue.shift();
const curPoint = pointQueue[0];
ctx.moveTo(...lastPoint);
ctx.lineTo(...curPoint);
}
ctx.stroke();
}
})(window, glMatrix);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment