Created
April 13, 2020 15:18
-
-
Save benbotto/6fb9c5cce83361c96efd4fb270d95bd3 to your computer and use it in GitHub Desktop.
Mirror a Line in a Canvas 1
This file contains hidden or 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 render() { | |
ctx.beginPath(); | |
ctx.lineWidth = 2; | |
while (pointQueue.length > 1) { | |
const lastPoint = pointQueue.shift(); | |
const curPoint = pointQueue[0]; | |
// First line: The line under the cursor. | |
ctx.resetTransform(); | |
ctx.moveTo(...lastPoint); | |
ctx.lineTo(...curPoint); | |
// Second line: Mirrored over the vertical line that passes through | |
// startPoint. | |
const toOrigin = gl.mat2d.fromTranslation( | |
gl.mat2d.create(), | |
gl.vec2.fromValues(-startPoint[0], 0) | |
); | |
const flipX = gl.mat2d.fromScaling( | |
gl.mat2d.create(), | |
gl.vec2.fromValues(-1, 1) | |
); | |
const fromOrigin = gl.mat2d.fromTranslation( | |
gl.mat2d.create(), | |
gl.vec2.fromValues(startPoint[0], 0) | |
); | |
const transform = mul(fromOrigin, flipX, toOrigin); | |
ctx.setTransform(...transform); | |
ctx.moveTo(...lastPoint); | |
ctx.lineTo(...curPoint); | |
} | |
ctx.stroke(); | |
} | |
// Helper function to multiply an arbitrary number of matrices together. | |
function mul(...mats) { | |
return mats.reduce( | |
(transform, mat) => gl.mat2d.multiply(transform, transform, mat), | |
gl.mat2d.create() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment