Home > Software engineering >  path2D rotation badworking
path2D rotation badworking

Time:11-17

I want to rotate objects using path2D but it doesn't rotate to size. While it works fine using ctx.rotate().

const ctx = document.body.appendChild(document.createElement('canvas')).getContext('2d')
let rotation = 45
let p1 = new Path2D()

p1.rect(0, 0, 75, 75)

let p2 = new Path2D()

p2.addPath(p1, new DOMMatrix().translate(10, 10).scale(1, 1.2).
rotate(rotation / 180 * Math.PI)) // 45deg not rotate

ctx.fillStyle = 'red'
ctx.fill(p2)

CodePudding user response:

The DOMMatrix interface takes rotation as degrees, not as radians. Yes, that's a shame that it's one of the only JS interfaces that does so, yes it's painful, everyday, but it's too late to make a change1.
For the history note, I believe it's because DOMMatrix is actually "a better SVGMatrix", and that SVGMatrix had it in degrees, because SVG has rotations only in degrees. DOMMatrix didn't have to deal only with degrees though, CSS can set angle units, and JS math operations are done in radians.

Anyway, that actually makes your code a bit simpler, though when you'll wan to roll back to a context transform you'll have to remember this discrepancy.

const ctx = document.body.appendChild(document.createElement('canvas')).getContext('2d')
let rotation = 45
let p1 = new Path2D()

p1.rect(0, 0, 75, 75)

let p2 = new Path2D()

p2.addPath(p1, new DOMMatrix().translate(10, 10).scale(1, 1.2).
rotate(rotation)) // in stoopid deg

ctx.fillStyle = 'red'
ctx.fill(p2)

1. Though if I get angry enough one of these days I may propose rotateRadians() et al. methods to be added...

  • Related