我正在使用 html 制作游戏,我需要以矩形底部为中心点旋转 Canvas 对象,但是我不确定这是否可以通过旋转方法实现。关于如何让它发挥作用有什么想法吗?谢谢。
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();}
最佳答案
您不需要使用 beginPath 和 fill 来填充矩形,您可以使用 fillRect 或 strokeRect。如果您设置转换,您还可以避免有时缓慢的保存和恢复功能。如果您只使用 setTransform,则除了剪辑之外,您不需要使用保存和恢复来进行任何操作。
代码的更快版本。
// 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
}
关于javascript - 有没有办法围绕其底部点而不是中心点旋转 Canvas 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706968/