Reputation: 799
Working on an open source project that we have HTML5 canvas rotation working for images and text - but I can't figure out what is different about shapes.
Source file: https://github.com/kageurufu/FaceMaker/blob/master/js/facemaker.render.js
Line 239:
case FM.ShapeTypes.square:
case FM.ShapeTypes.line:
//As far as I can tell, a line is just a rect, and a square is really a rect
if (layer.shape_opt === 0) {
c.fillRect(x, y, fm.parseInt(layer.width), fm.parseInt(layer.height));
} else {
c.strokeRect(x, y, fm.parseInt(layer.width), fm.parseInt(layer.height));
}
This works, to draw a dynamic line width the provided variables: x,y,width,height.
However, we have a rotation variable that is 0..360 and if > 0 it needs to be applied. For images and fonts, we rotate the canvas like this at line 298:
c.save();
c.translate(x, y);
c.rotate(rotation * (Math.PI / 180));
// draw here
c.restore();
However... I can't figure out how to do this with lines. I've read the other related questions here - but not understanding how to adjust the origin of a shape.
Upvotes: 0
Views: 606
Reputation: 105015
To rotate a line around its centerpoint:
Calculate the bounding box of the line: minX,minY,maxX,maxY
Translate to the bounding box centerpoint: translate( minX+(maxX-minX)/2, minY+(maxY-minY)/2 )
Rotate as desired
Clean up by first unrotating & then untranslating the canvas.
Upvotes: 1