我希望在调用函数时效果立即运行,但是当我调用函数时我必须等待 3-4 秒才能生效。
我在 HTML 中使用画布
const canvas = document.querySelector("#draw-pad");
const ctx = canvas.getContext("2d");
function runTextAnimation(text) {
var x = canvas.width / 2;
var y = canvas.height / 2;
var txt = text;
var w = 0;
var clearH = 40;
var clearY = 5;
var clearX = 8;
ctx.font = 'bold 17px Arial';
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
function runText() {
if (w > 500) {
ctx.clearRect(clearX, clearY, w, clearH);
w = 0;
}
if (w === 0) {
ctx.fillStyle = 'lightblue';
ctx.strokeText(txt, x, y);
ctx.fillText(txt, x, y);
ctx.fillStyle = 'red';
}
ctx.save();
ctx.beginPath();
ctx.clearRect(clearX, clearY, w, clearH);
ctx.rect(clearX, clearY, w, clearH);
ctx.clip();
ctx.strokeStyle = 'white';
ctx.strokeText(txt, x, y);
ctx.fillText(txt, x, y);
ctx.restore();
w += 1.92;
window.requestAnimationFrame(runText);
}
runText();
}
runTextAnimation("chắc không phải một người như anh")
<canvas id="draw-pad" width="578" height="50"></canvas>
我希望在调用函数时效果立即运行,但是当我调用函数时我必须等待 3-4 秒才能生效。
您可以简单地使用
substring
绘制部分文本,而不是使用clearRect 和所有其他复杂性,您的代码将明显更小,(并且在我眼中更容易阅读)我还使用 setInterval
来更好地控制字母之间的时间延迟
const canvas = document.querySelector("#draw-pad");
const ctx = canvas.getContext("2d");
const delay = 100
var w = 0
function textAnimation(text, x, y) {
ctx.reset();
ctx.font = 'bold 17px Arial';
ctx.lineWidth = 4;
ctx.fillStyle = 'lightblue';
ctx.fillText(text, x, y);
ctx.fillStyle = 'red';
ctx.fillText(text.substring(0, w), x, y);
if (w++ > text.length) w = 0
}
setInterval(() => textAnimation("chắc không phải một người như anh", 300, 20), delay)
<canvas id="draw-pad" width="600" height="50"></canvas>