简体   繁体   中英

Is there a way to rotate a canvas object around its bottom point rather than its center point

I am making a game using html, and I need to rotate a canvas object with the bottom of the rectangle as the centerpoint, however i'm not sure if this is possible through the rotate method. Any ideas on how to get this working? Thanks.

function drawRotatedRect(x, y, width, height, degrees, color) {
    context.save();
    context.beginPath();
    context.translate(x + width / 2, y + height / 2);
    context.rotate(degrees*Math.PI/180);
    context.rect(-width / 2, -height / 2, width, height);
    context.fillStyle = color;
    context.fill();
    context.restore();}

它与创建矩形的前2个参数有关,已经解决了

You don't need to use beginPath and and fill for rectangle you can use fillRect or strokeRect. Also you can avoid the sometime slow save and restore functions if you set the transform. If you only use setTransform you will not need to use save and restore for anything but clipping.

A quicker version of your code.

// where centerX and centerY is where the rotation point is on the rectange    
function drawRotatedRect(x, y, width, height, centerX, centerY, rotation, color) {
    context.setTransform(1, 0, 0, 1, x, y);
    context.rotate(rotation);
    context.fillStyle = color;
    context.fillRect(-centerX, -centerY, width, height);
    context.setTransform(1, 0, 0, 1, 0, 0); // restore default Only needed if 
                                            // you transform not using setTransform 
                                            // after this call
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM