๐ฐtransformation
Last updated
Last updated
browser โฉ canvas โฉ state โฉ current transformation matrix
.translate(), .rotate(), .scale() will alter the current transformation matrix.
examples
replit๏ผcanvas transformations
โฌ๏ธ ้่ฆ๏ผ drawOnCanvas2D()
const { PI } = Math;
const { log } = console;
// degrees
function deg(x) { return PI * x / 180 }
// draw on canvas
drawOnCanvas2D('#playground', (ctx) => {
const rect = [0, 0, 80, 80];
// tranform and draw square
function transform(hue, trans){
// transform current transformation matrix if necessary
if (trans) trans(ctx);
// log current transformation matrix
const {a,b,c,d,e,f} = ctx.getTransform();
log([a,b,c,d,e,f]);
// draw rect with specified hue
ctx.fillStyle = `hsl(${hue} 80% 50% / 0.8)`;
ctx.fillRect(...rect);
ctx.strokeRect(...rect);
}
// original square
transform(0);
// translate
transform(30, (ctx) => ctx.translate(110, 30));
// rotate
transform(60, (ctx) => ctx.rotate(deg(60)));
// dilate (scale)
transform(90, (ctx) => ctx.scale(.5, .5));
// freeform transform
transform(180, (ctx) => ctx.transform(1, .5, .5, 1, 0, 0));
// reset current transformation matrix to identity
ctx.setTransform(1, 0, 0, 1, 0, 0);
// scale
transform(210, (ctx) => ctx.scale(.25, 2));
});
current transformation matrix
.setTransform() - overrides the current transformation matrix.
.getTransform() - returns DOMMatrix.
apply transformations to current transformation matrix: