0

I need to draw a rotated rectangle in canvas by its center point, but I want to set a x and y to it. I'm actually moving the rectangle to $b.width / 2 and $b.height / 2. I don't know how to do that.

This is my class code. Note: $b is my rectange.

do {
    switch($b.t) {
        case 0: { // draw rectangle
            context.fillStyle = $b.tint;
            if($b.rotate) {
                context.save();
                context.translate($b.width, $b.height);
                context.rotate(($b.rotate * Math.PI) / 180);
                context.fillRect(-$b.width / 2, -$b.height / 2, $b.width, $b.height);
                context.restore();
            }else{
                context.fillRect($b.width / 2, $b.height / 2, $b.width, $b.height);
            }
            break;
        }
    }
} while($b = queue[$i ++]);

1 Answer 1

0

So you want a to set the centerpoints of a rectangle that's rotating around it's own centerpoint?

Just add your desired x,y to the initial translation:

Note: Since you're doing simple, un-nested transformations, undo the transformations in the reverse order. Context save & restore will work, but you're saving /restore all the other context properties so it's not as efficient.

// translate (including the desired centerX & center)
context.translate(x+b.width/2,y+b.height/2);

// rotate
context.rotate(($b.rotate * Math.PI) / 180);

// fill the rect offset by half its size
context.fillRect(-$b.width / 2, -$b.height / 2, $b.width, $b.height);

// unrotate
context.rotate((-$b.rotate * Math.PI) / 180);

// untranslate
context.translate(-x-b.width/2,-y-b.height/2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy