我想更改画布上的文本。问题是,当我从输入中删除字母时,它只是添加而不是删除字母。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.change = function(val){
ctx.restore();
ctx.font = "20px Georgia";
ctx.fillText(val, 10, 50);
ctx.save();
}
<canvas id="myCanvas"></canvas>
<input type="text" onkeyup="change(this.value)" />
为什么添加文本有效,而删除却无效。你能纠正一下吗?
谢谢
答案 0 :(得分:3)
尝试一下:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.change = function(val){
ctx.clearRect(0, 0, c.width, c.height);
ctx.restore();
ctx.font = "20px Georgia";
ctx.fillText(val, 10, 50);
ctx.save();
}
请参阅工作示例here
更新。 如果您具有后台添加功能:
function fillBackground() {
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, c.width, c.height);
}
然后在window.change之前和ctx.clearRect之后使用它
答案 1 :(得分:1)
**Please try this :**
window.change = function(val){
ctx.clearRect(0, 0, a.width, a.height);
ctx.restore();
ctx.font = "20px Georgia";
ctx.fillText(val, 10, 50);
ctx.save();
}
**The clearRect() method sets the pixels in a rectangular area to transparent black
(rgba(0,0,0,0)). The rectangle's corner is at (x, y), and its size is specified by
width and height.**
x
The x-axis coordinate of the rectangle's starting point.
y
The y-axis coordinate of the rectangle's starting point.
width
The rectangle's width. Positive values are to the right, and negative to the left.
height
The rectangle's height. Positive values are down, and negative are up.