Svg Path Data in Canvas
Building canvas shapes with svg path data
Typically most canvas drawing requires a series of commands. Something like this.
ctx.beginPath();
ctx.moveTo(150, 10);
ctx.lineTo(115, 70);
ctx.lineTo(185, 70);
ctx.closePath();
ctx.stroke();
This gives us a triangle.
However,using Path2D
we can utilize the common svg path data commands to accomplish this. In my opinion this is much more simple.
const p = new Path2D('M150 10 L115 70 L185 70 Z');
ctx1.stroke(p);
If you're not familiar with svg path data commands I have a short series to ramp you up.
Moreover there are a ton of svg path libraries out there that can simplify this even further. I'll tout my own library in this next example.
import Path from "@joemaddalone/path";
const p = new Path2D(new Path().triangle(70, 150, 50).toString());
ctx.stroke(p);
And with that we're off to the races. This next part is a bit "draw the rest of the fucking owl"
import Path from "@joemaddalone/path";
let cx = 0;
let cy = 0;
let moveX = 1;
let moveY = 1;
const size = 20
const halfSize = size/2;
const c = document.getElementById("canvas");
const ctx = c.getContext('2d');
const { x, y } = c.getBoundingClientRect();
const outOfBounds = (pos, end) => pos + size > end || pos < 0;
const update = () => {
ctx.clearRect(0, 0, c.width, c.height);
moveY = outOfBounds(cy + moveY, c.height) ? -moveY : moveY
moveX = outOfBounds(cx + moveX, c.width) ? -moveX : moveX
cx += moveX;
cy += moveY;
const sq = new Path().square(size, cx + halfSize, cy + halfSize)
ctx.stroke(new Path2D(sq.toString()));
requestAnimationFrame(update);
}
update();