Skip to content

Instantly share code, notes, and snippets.

@benbotto
Created April 13, 2020 15:18
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/6fb9c5cce83361c96efd4fb270d95bd3 to your computer and use it in GitHub Desktop.
Save benbotto/6fb9c5cce83361c96efd4fb270d95bd3 to your computer and use it in GitHub Desktop.
Mirror a Line in a Canvas 1
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