RoundSparrow hilltx
RoundSparrow hilltx

Reputation: 799

HTML5 Drawing with canvas, rotate line?

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

Answers (1)

markE
markE

Reputation: 105015

To rotate a line around its centerpoint:

  1. Calculate the bounding box of the line: minX,minY,maxX,maxY

  2. Translate to the bounding box centerpoint: translate( minX+(maxX-minX)/2, minY+(maxY-minY)/2 )

  3. Rotate as desired

  4. Clean up by first unrotating & then untranslating the canvas.

Upvotes: 1

Related Questions