【发布时间】:2020-04-07 00:16:35
【问题描述】:
我是 HTML5 画布的新手,做了一个简单的文本动画。
但是,当动画正在进行时,我无法清除之前绘制的文本。文本看起来被拖了。请在下面找到代码链接以获得清晰的图片。点击动画按钮查看动画。
function drawTextOnCanvas(
can,
ctx,
text,
font,
backColor,
textColor,
maxWidth,
startingx,
startingy,
spacing
) {
var linesArray = getLines(ctx, text, maxWidth);
ctx.save();
for (var i = 0; i < linesArray.length; i++) {
drawTextBG(
can,
ctx,
linesArray[i],
font,
backColor,
textColor,
startingx,
startingy
);
// ctx.fillText(linesArray[i], startingx, startingy);
/* startingx += spacing; */
startingy += spacing; // Remove this if you want everthing in line
}
ctx.restore();
}
function getLines(ctx, text, maxWidth) {
// Enter maxWidth depending on the resolution and canvas dimensions
var words = text.split(" ");
var lines = [];
var currentLine = words[0];
ctx.font = "54px bolder Arial"
for (var i = 1; i < words.length; i++) {
var word = words[i];
var width = ctx.measureText(currentLine + " " + word).width;
if (width < maxWidth) {
currentLine += " " + word;
} else {
lines.push(currentLine);
currentLine = word;
}
}
lines.push(currentLine);
return lines;
}
function drawTextBG(can,ctx, txt, font, backColor, textColor, x, y) {
/// set font
console.log(txt)
x= -300;
let speed = 15;
let distance = 0;
var startTime = new Date().getTime();
var interval = setInterval(function() {
if (new Date().getTime() - startTime > 1000) {
clearInterval(interval);
}
if (distance >= 600) {
distance = 0;
// clearInterval(interval);
x = canv.width / 2;
}
distance += speed;
animateText(can,ctx, txt, font, backColor, textColor, x + distance, y);
}, 33);
}
function animateText(can,ctx, txt, font, backColor, textColor, x, y) {
ctx.font = font;
/// draw text from top - makes life easier at the moment
ctx.textBaseline = "top";
/// color for background
ctx.fillStyle = backColor;
/// get width of text
var width = ctx.measureText(txt).width;
/// draw background rect assuming height of font
ctx.fillRect(x, y, width, parseInt(font, 10));
/// text color
ctx.fillStyle = textColor;
/// draw text on top
ctx.fillText(txt, x, y);
}
这是Fiddle
帮助我获得完美的动画。提前致谢!
【问题讨论】:
标签: javascript html canvas html5-canvas