我已将文本放在<canvas>标签中的图像上(文本来自输入框).
现在,如果我在上面添加一个新文本<canvas>,则强加于之前的文本.在放入新文本之前,如何清除画布上的现有文本?
我已经尝试通过分配重置画布,canvas.width但文本保持打开状态.有人帮忙吗?
如果您知道要添加和删除大量文本,那么跟踪旧文本可能是有意义的.然后你可以使用这个:
context.fillStyle = '#ffffff'; // or whatever color the background is.
context.fillText(oldText, xCoordinate, yCoordinate);
context.fillStyle = '#000000'; // or whatever color the text should be.
context.fillText(newText, xCoordinate, yCoordinate);
Run Code Online (Sandbox Code Playgroud)
这样您就不必每次都重绘整个画布.
您使用context.clearRect(),但首先必须弄清楚要清除的矩形.这基于许多因素,例如文本的大小和最初绘制文本时画布上下文的textAlign属性.下面的代码用于绘制文本到画布上下文的对象的绘制方法,因此它具有x,y,文本大小,水平对齐等属性.请注意,我们总是存储绘制的最后一段文本,所以我们可以在下次更改值时清除适当大小的矩形.
this.draw = function() {
var metrics = this.ctx.measureText(this.lastValue),
rect = {
x: 0,
y: this.y - this.textSize / 2,
width: metrics.width,
height: this.textSize,
};
switch(this.hAlign) {
case 'center':
rect.x = this.x - metrics.width / 2;
break;
case 'left':
rect.x = this.x;
break;
case 'right':
rect.x = this.x - metrics.width;
break;
}
this.ctx.clearRect(rect.x, rect.y, rect.width, rect.height);
this.ctx.font = this.weight + ' ' + this.textSize + ' ' + this.font;
this.ctx.textAlign = this.hAlign;
this.ctx.fillText(this.value, this.x, this.y);
this.lastValue = this.value;
}
Run Code Online (Sandbox Code Playgroud)
我不确定在放置下一段文本之前如何清除图像上的文本。
如果画布的背景是恒定的;您只需更改文本即可将两个画布元素分层。背景和透明的文本顶层,当您想要更新文本时,可以将其删除并插入新的文本。