问题描述
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const image = new Image(60,45); // Using optional size for image
image.onload = drawImageActualSize; // Draw when image has loaded
// Load an image of intrinsic size 300x227 in CSS pixels
image.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
function drawImageActualSize() {
// Use the intrinsic size of image in CSS pixels for the canvas element
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
// Will draw the image as 300x227,ignoring the custom size of 60x45
// given in the constructor
ctx.drawImage(this,0);
// To use the custom size we'll have to specify the scale parameters
// using the element's width and height properties - lets draw one
// on top in the corner:
ctx.drawImage(this,this.width,this.height);
ctx.save();
ctx.fillStyle = 'green';
ctx.fillRect(10,10,150,100);
ctx.restore();
ctx.clearRect(10,100);
}
<canvas id="canvas" width=300 height=200></canvas>
这里ctx.clearRect(10,10,150,100)方法,除去绿色部分和图像,并显示白色画布。
我只想删除绿色部分并恢复以前的图像。
我该如何实现?
解决方法
重画
添加和删除动态内容的标准方法是在每次更改时重新渲染画布。这就是运行60fps的HTML画布游戏的方式,并且每帧可以更改100项。
还有其他方法需要在每次绘制矩形时都对其进行复制,然后在要删除矩形时在矩形上绘制副本。
这很复杂,每个动态对象绘制至少需要一个额外的画布,因此是一个内存消耗。或同时使用getImageData
和putImageData占用大量内存,速度非常慢,将导致大量的GC操作,并且不适用于不安全的内容(跨域或本地文件存储的图像)。
重绘是迄今为止最简单的方法。如果仅花费多于100毫秒的时间渲染所有内容(对于非动画内容),您将只考虑其他方法
示例
在示例中,变量rectOn
如果为true,则向画布添加一个绿色矩形(同时绘制图像和矩形)。如果不正确,则删除矩形(仅绘制图像)。
函数draw
根据变量rectOn
的状态渲染画布。
单击按钮添加/删除矩形。
const ctx = canvas.getContext('2d');
var rectOn = false;
const image = new Image();
image.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
image.addEventListener("load",ready,{once:true});
function ready() {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
loading.classList.add("hide");
addRemove.classList.remove("hide");
addRemove.addEventListener("click",toggle);
draw();
}
function draw() {
ctx.drawImage(image,0);
if (rectOn) {
ctx.fillStyle = "#0F0";
ctx.fillRect(10,50,150,100);
}
}
function toggle() {
rectOn = !rectOn;
addRemove.textContent = (rectOn ? "Remove": "Add" ) + " rect";
draw();
}
button { cursor: pointer; width: 120px }
.hide {display:none}
canvas { position: absolute; top: 0px; left: 0px; z-index:-1; }
<span id="loading">Loading image</span><button id="addRemove" class="hide">Add green rect</button><br>
<canvas id="canvas"></canvas>