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

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

问题描述

我使用 HTML5 画布如下:

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.

带有 9 个参数的 drawImage 仅重绘更改后的背景图像部分,然后重绘黑色文本.

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) 到 (180,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 Canvas 的背景区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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