javascript - 有没有办法围绕其底部点而不是中心点旋转 Canvas 对象

标签 javascript canvas html5-canvas

我正在使用 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/

相关文章:

javascript - HTML5 Canvas 围绕圆点旋转多个文本项

javascript - 网站上的 3D 图形非常酷,但这背后的技术是什么?

javascript - 动态计算元素集之间的高度

javascript - 为什么 charAt 检测不到字符串?

javascript - 无法使用删除事件监听器

javascript - 如何平滑我的 JavaScript 动画?

javascript - 如何在div之间绘制响应线

javascript - Redux 展示组件与容器组件

javascript - 基于六边形网格的html5/canvas游戏框架

javascript - 使用 Konva.Layer 进行拖动绑定(bind)