且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从画布中添加和删除(多个)图像。

更新时间:2023-12-05 16:32:52

HTML5画布就像一个真实世界的画布。

An HTML5 Canvas is much like a real-world canvas. When you draw to the canvas the ink changes the canvas, blending with the other contents already there and forever changing them.

问Monet

Ask Monet "How do you add a new person to your painting?" and he might say "you just paint them where you want them!" Similarly, you use drawImage() to 'paint' an image to your Canvas.

但是,如果你问莫奈,你如何删除一个人一个绘画?,他可能会看着你有趣,然后回应你要做一个新的画,或者画在人的顶部 ,如果你想从画布中移除某些东西,你必须重新开始(清除画布并绘制除该东西以外的所有东西),或者重新绘制您的图像之上的背后。

However, if you ask Monet "How do you remove a person from a painting?" and he would likely look at you funny and then respond "Quoi? You would have to either make a new painting, or else paint over top of the person!" Similarly, if you want to "remove" something from your canvas you either have to start over (clear the canvas and draw everything except that thing) or re-paint what was 'behind' your image on top of it.

这是我做的一个例子,显示了一种可以保存

Here is an example I made that shows one way that you can 'save' part of a canvas (by drawing it to another canvas) and then later drawing it back over something to 'erase' it.

但是,我一般建议你不要使用一个画布的一部分(通过绘制到另一个画布)一个HTML5画布,除非你知道为什么你需要它。你提到添加和删除项目,以及检测鼠标移动。使用保留模式绘图系统(例如HTML或SVG)意味着您实际上添加或删除或更改对象表示中的项目,而由其他人(浏览器)***重新绘制它们。

However, I generally advise you not to use an HTML5 Canvas unless you know why you need it. You mention adding and removing items, and also detecting mouse movements. Using a retained-mode drawing system—like HTML or SVG—means that you actually add or remove or change items in an object representation, and it is up to someone else (the browser) to figure out how to best redraw them.

您可以通过让用户输入的绘制部分在一个或多个画布上完成,然后将这些画布合成其他项目(例如用于图片的< div> s或者用于图片的< img> 基于SVG的艺术品)。

You may be best served by letting the "paint" portions of the user input be done on one or more canvases, and then compositing these canvases with other items (such as <div>s with text, or <img> for pictures, or vector-based SVG artwork).

您可以在画布类型上制作您自己的保留模式系统,也可以使用其他人的库执行此操作。但我建议您考虑这是否是实现您的目标的***和最简单的方法。

You can make your own retained-mode system on type of canvas, or you can use someone else's library that does this. But instead I'd suggest that you consider whether this is the best and easiest way to accomplish your goals.