I have a path that I want to render fully in a canvas. I know the initial width and height on the path but I want to rotate and scale it.
So I figured out how to determine the new canvas size but this code isn't doing what I'd like:
let [w, h] = json.imgSize;
ctx.translate(-w / 2, -h / 2);
ctx.scale(json.scale, json.scale);
ctx.rotate(json.rotation);
[w, h] = [canvas.width, canvas.height];
ctx.translate(w / 2, h / 2);
I would expect the result to be the path scaled and rotated but still in the center of the canvas. Instead it is rotating about the top-left corner of the path.
My reasoning is this:
- move the path center to coordinate 0,0
- scale the resulting image about its center
- rotate the image about its center
- move the resulting image to the canvas center
Here is how I calculate the canvas size:
// rotate a rectangle and get the resulting extent
let [x, y] = json.imgSize;
let coords = [[-x, -y], [-x, y], [x, y], [x, -y]];
let rect = new ol.geom.MultiPoint(coords);
rect.rotate(json.rotation, [0, 0]);
let extent = rect.getExtent();
[canvas.width, canvas.height] = [ol.extent.getWidth(extent), ol.extent.getHeight(extent)].map(v => v * 0.5);