在画布上绘制旋转的元素 [英] Draw a rotated element on a canvas

查看:75
本文介绍了在画布上绘制旋转的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不旋转画布的情况下在旋转的画布上绘制一个半复杂的元素,这样就无需计算该元素的所有x/y点.

I want to draw a semi-complex element on a canvas rotated without rotating the canvas so that I don't need to calculate all of the various x/y points of the element.

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

I think that the basic process I need to use is:

  • 将0,0点转换为绘制元素将旋转的点,
  • 旋转画布,
  • 绘制元素,
  • 将画布向后旋转,
  • 还原原点.

我将需要多次执行此操作.我读过,旋转/向后旋转部分可能会引入一些错误,最终图像会稍微偏离一点.有办法避免这种情况吗?

I will need to do this more than once. I've read that the rotate / rotate back part can introduce some error, with the final image being off just a bit. Is there a way to avoid this?

推荐答案

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

Before you perform the rotation and translation, call context.save(). This will create a snapshot of the current transformation of the canvas (as well as some other things, like drawing style, clip region, etc., but not the pixel data) and store it on a stack.

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

After you drew the shape, call context.restore(). This will pop the last saved state from the state stack and restore the current drawing state of the canvas to it.

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

You can do this as often as you want without accumulating any rounding differences.

示例功能:

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
}

有关画布状态的更多信息,请参考画布规范.

For more information about the canvas state, refer to the canvas specification.

这篇关于在画布上绘制旋转的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆