在 canvas 上绘制旋转元素

Draw a rotated element on a canvas

我想在不旋转 canvas 的 canvas 上绘制一个半复杂元素,这样我就不需要计算 x/y 的所有不同点元素。

我认为我需要使用的基本流程是:

我需要不止一次这样做。我读到旋转/向后旋转部分会引入一些错误,最终图像会稍微偏离一点。有没有办法避免这种情况?

在执行旋转和平移之前,请调用 context.save()。这将创建 canvas 当前变换的快照(以及其他一些东西,如绘图样式、剪辑区域等,但不包括像素数据)并将其存储在堆栈中。

画好形状后,调用context.restore()。这将从状态堆栈中弹出最后保存的状态,并将 canvas 的当前绘图状态恢复到它。

您可以根据需要多次执行此操作,而不会累积任何舍入差异。

示例函数:

function drawImageRotated(x, y, rotation, image) {
    context.save();

    context.translate(x, y);
    context.rotate(rotation);
    context.drawImage(image, -image.width / 2, -image.height / 2);        

    context.restore();

    // context translation and rotation are now on the same state they were
    // before the function call
}

有关 canvas 状态的详细信息,请参阅 the canvas specification