If I use a transformation function like translate
/rotate
on a canvas, then all points are transformed when passed to any canvas function. This works like a charm, but is there also a way to simply get the transformed point without actually drawing?
This will be extremely helpful when debugging. All I can do now is looking where the point ends up, but I cannot seem to obtain the calculated transformed coordinates.
So, say I rotate 90 degrees, is there any function that takes a point (i.e. (10, 0)
) and gives the transformed point back (i.e. (0, 10)
)?
I basically mean something like this:
ctx.rotate(90 * Math.PI / 180);
ctx.transformed(10, 0); // would return (0, 10) as an array or something
This is possible now, using the DOMMatrix returned from CanvasRenderingContext2D.getTransform():
const point = {x: 0, y: 0};
const matrix = ctx.getTransform();
const transformedPoint = {
x: matrix.a * point.x + matrix.c * point.y + matrix.e,
y: matrix.b * point.x + matrix.d * point.y + matrix.f,
};
The short answer is 'not by default.'
You will need to keep track the current transformation yourself because there is no way to get it (people have submitted bugs because this seems so unnecessary).
Libraries like Cake.js, and a lot of us, essentially duplicate the transformation code in order to keep track of it so we can do stuff like this. Once you keep track of it, all you need is:
function multiplyPoint(point) {
return {
x: point.x * this._m0 + point.y * this._m2 + this._m4,
y: point.x * this._m1 + point.y * this._m3 + this._m5
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With