保存画布然后还原,为什么呢? [英] Save canvas then restore, why is that?

查看:77
本文介绍了保存画布然后还原,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到以下代码

canvas.save().
canvas translate or rotate
some drawing
canvas.restore

我不明白为什么我们先保存然后再恢复.撤销我们刚刚做的事情有什么意义!我确定我在这里想念什么 谢谢

I don't understand why we save and then restore. What's the point of undoing what we just did! I am sure I am missing something here Thanks

推荐答案

我知道这个问题有些陈旧,但对于仍在寻找答案的人,我可以ELI5;

I understand this question is a bit dated, but for anyone still looking for an answer I can ELI5;

想象一下,画布是一张纸,您的任务是在右上方(底部)绘制一个机器人的图片,在另一侧(底部)绘制一个机器人的图片,稍微向右移动,将其缩小约40%.顶端.像这样的东西;

Imagine the canvas is a piece of paper, and you're tasked with drawing a picture of a robot right side up, at the bottom, and another robot upside down, slightly moved to the right, and about 40% smaller at the top. Something like this;

您将如何开始?首先更容易做些什么?

How would you start? What's easier to do first?

您可能会首先在底部绘制较大的机器人,因为它朝上,并且朝着更自然的方向绘制要容易得多.因此,您已经完成了第一个,现在如何处理第二个倒置机器人?

You would probably draw the bigger robot at the bottom first since it's right-side up and it's a lot easier to draw in the direction that feels more natural. So you've got the first one done, now how do you approach the second upside down robot?

  • 您可以尝试按原样绘制它,但这会有些困难,因为您的颠倒了.

  • 您可以将纸张旋转180°,稍微移动起点,然后以较小的比例开始绘制,完成之后,您只需向后旋转纸张即可.

这是canvas.save()canvas.restore()的工作,它们允许您以任何使自己更轻松地绘制所需内容的方式修改画布.您不需要使用这些方法,但是它们确实可以简化很多过程.上面看起来像

This is what canvas.save() and canvas.restore() do, they allow you to modify your canvas in any way that makes it easier for you to draw what you need. You don't need to use these methods, but they sure do simplify a lot of the process. The above would look something like

drawRobot()
canvas.save()
canvas.rotate(180)
canvas.translate(100, 0)
canvas.scale(40,40)
drawRobot()
canvas.restore()

如果我们查看restore()文档,则显示为

If we look at the restore() documentation it says

用于删除自上次保存调用以来对矩阵/剪辑状态的所有修改

并查看这些修改是什么,我们来看看save()它说的

and to see what those modifications are we take a look at save() it says

翻译,缩放,旋转,倾斜,concat或clipRect,clipPath

translate, scale, rotate, skew, concat or clipRect, clipPath

好吧,实际上我们确实使用了translate rotatescale,但是我们也调用了drawRobot(),所以不调用restore会删除我们的图形吗?否,因为它不会影响图形,因此进行修改.因此,当我们调用restore时,它将使画布返回到开始第二个绘图之前的状态.

Well look at that, we did in fact use translate rotate and scale but we also did call drawRobot() so wouldn't calling restore erase our drawing? No, because it doesn't affect the drawing, only the modifications. So when we call restore it will return our canvas to the state that it was in before we started the second drawing.

这篇关于保存画布然后还原,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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