保存/恢复HTML5画布的背景区域 [英] Save/restore background area of HTML5 Canvas

查看:119
本文介绍了保存/恢复HTML5画布的背景区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HTML5 canvas,如下所示:

I am using HTML5 canvas as follows:


  1. 显示填充画布区域的图片。

  2. 在图片上方显示黑色文字标签。

  3. 点击文字标签时,可以通过绘制一条红色直线和白色文字来突出显示。

我有一部分工作正常。现在我想做的是删除红色的矩形,并恢复最初在其背后的图像背景。我是新的画布,并已阅读了一个相当数量,但我不能看到如何做到这一点。

I have that part all working fine. Now what I want to do is remove the red rect and restore the image background that was originally behind it. I'm new to canvas and have read a fair amount, however I can't see how to do this. That said I am sure it must be quite simple.

推荐答案

我认为有一些方法...

I think there are some ways...

这很简单,但效率不高。

This is simple but not really efficient.

drawImage带有9个参数,仅重绘已更改的背景图片部分,然后重新绘制黑色文本。

drawImage with 9 arguments to redraw only the altered background image part, then redraw the black text over.

这使用2D上下文的getImageData和putImageData。

This uses getImageData and putImageData of the 2D context. (Not sure that it's widely implemented though.)

这里的规格:

ImageData getImageData(in double sx, in double sy, in double sw, in double sh);
void putImageData(in ImageData imagedata, in double dx, in double dy, in optional double dirtyX, in double dirtyY, in double dirtyWidth, in double dirtyHeight);

因此,例如如果更改的部分位于(20,30) 70)像素,只需:

So for instance if the altered part is in the rect from (20,30) to (180,70) pixels, simply do:

var ctx = canvas.getContext("2d");
var saved_rect = ctx.getImageData(20, 30, 160, 40);
// highlight the image part ...

// restore the altered part
ctx.putImageData(saved_rect, 20, 30);



使用两个叠加的画布



画布,位于第一个,将保持红色矩形和白色文本,并将被清除时,你想恢复原始图像。

Use two superposed canvas

The second canvas, positioned over the first, will hold the red rect and the white text, and will be cleared when you want to "restore" the original image.

这篇关于保存/恢复HTML5画布的背景区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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