Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/453.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 画布:删除图像上的对象后恢复图像_Javascript_Html_Html5 Canvas - Fatal编程技术网

Javascript 画布:删除图像上的对象后恢复图像

Javascript 画布:删除图像上的对象后恢复图像,javascript,html,html5-canvas,Javascript,Html,Html5 Canvas,我有以下代码: const canvas=document.getElementById('canvas'); const ctx=canvas.getContext('2d'); 常量图像=新图像(60,45);//对图像使用可选大小 image.onload=drawImageActualSize;//加载图像后绘制 //加载内部大小为300x227(CSS像素)的图像 image.src=https://mdn.mozillademos.org/files/5397/rhino.jpg'

我有以下代码:

const canvas=document.getElementById('canvas');
const ctx=canvas.getContext('2d');
常量图像=新图像(60,45);//对图像使用可选大小
image.onload=drawImageActualSize;//加载图像后绘制
//加载内部大小为300x227(CSS像素)的图像
image.src=https://mdn.mozillademos.org/files/5397/rhino.jpg';
函数drawImageActualSize(){
//使用画布元素的图像固有大小(以CSS像素为单位)
canvas.width=this.naturalWidth;
canvas.height=this.naturalHeight;
//将图像绘制为300x227,忽略自定义尺寸60x45
//在构造函数中给出
ctx.drawImage(this,0,0);
//要使用自定义尺寸,我们必须指定比例参数
//使用元素的宽度和高度属性-让我们绘制一个
//在角落的顶部:
ctx.drawImage(this,0,0,this.width,this.height);
ctx.save();
ctx.fillStyle='绿色';
ctx.fillRect(10,10,150,100);
ctx.restore();
ctx.clearRect(10,10,150,100);
}
重画 添加和删除动态内容的标准方法是每次更改时重新渲染画布。这就是以每秒60帧的速度运行的HTML画布游戏的方式,每帧可以更改100个项目

还有其他一些方法需要在每次绘制矩形时复制矩形下的内容,然后在需要删除矩形时在矩形上绘制副本

这很复杂,每个正在绘制的动态对象至少需要一个额外的画布,因此占用内存。或者使用,同时也是内存占用,速度很慢,将导致大量GC操作,并且不适用于不安全的内容(跨域的图像或来自本地文件存储的图像)

重画是迄今为止最简单的方法。如果需要超过100Ms来渲染所有内容(对于非动画内容)

,您只会考虑其他方法。 例子 在本例中,变量
rectOn
if true将绿色矩形添加到画布(绘制图像和矩形)。如果不为true,则删除矩形(仅绘制图像)

函数
draw
根据变量
rectOn

单击按钮添加/删除矩形

const ctx=canvas.getContext('2d');
var-rectOn=false;
常量图像=新图像();
image.src=https://mdn.mozillademos.org/files/5397/rhino.jpg';
addEventListener(“load”,ready,{once:true});
函数就绪(){
canvas.width=this.naturalWidth;
canvas.height=this.naturalHeight;
loading.classList.add(“hide”);
addRemove.classList.remove(“隐藏”);
addRemove.addEventListener(“单击”,切换);
draw();
}
函数绘图(){
ctx.drawImage(图像,0,0);
if(rectOn){
ctx.fillStyle=“#0F0”;
ctx.fillRect(10,50,150,100);
}
}
函数切换(){
rectOn=!rectOn;
addRemove.textContent=(rectOn?“Remove”:“Add”)+“rect”;
draw();
}
按钮{光标:指针;宽度:120px}
.hide{显示:无}
画布{位置:绝对;顶部:0px;左侧:0px;z索引:-1;}
加载图像添加绿色矩形