简体   繁体   English

有没有办法围绕底点而不是中心点旋转画布对象

[英]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. 我正在使用html制作一个游戏,我需要旋转一个画布对象,矩形的底部作为中心点,但是我不确定这是否可以通过rotate方法。 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. 您不需要使用beginPath和填充矩形,您可以使用fillRect或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. 如果您只使用setTransform,除了裁剪之外,您不需要使用保存和恢复。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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