我无法弄清楚您的 Text 构造函数是如何工作的。所以我写了一个独立的函数(不属于任何对象)。您需要传递给此函数的只是一个字符串、X 和Y 位置、行高和填充。它假设画布分配给变量canvas,二维上下文分配给变量ctx。
var canvas, ctx;
function typeOut(str, startX, startY, lineHeight, padding) {
var cursorX = startX || 0;
var cursorY = startY || 0;
var lineHeight = lineHeight || 32;
padding = padding || 10;
var i = 0;
$_inter = setInterval(function() {
var w = ctx.measureText(str.charAt(i)).width;
if(cursorX + w >= canvas.width - padding) {
cursorX = startX;
cursorY += lineHeight;
}
ctx.fillText(str.charAt(i), cursorX, cursorY);
i++;
cursorX += w;
if(i === str.length) {
clearInterval($_inter);
}
}, 75);
}
查看演示 here。
提示-
我正在浏览您的代码并找到了一些链接-
function Rectangle(x,y,width,height,colour) {
//properties
this.draw = function() { //Don't assigns object methods through constructors
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
您不应该通过构造函数向对象添加方法,因为它会在每次实例化对象时创建方法。而是将方法添加到对象的原型中,这样,它们将只创建一次,并由所有实例共享。喜欢-
function Rectangle(x,y,width,height,colour) {
//properties
}
Rectangle.prototype.draw = function() {
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
另外,我发现您正在创建额外的变量来指向某些对象。喜欢 -
var that = this;
var fadeIn = setInterval(function() {
//code
that.draw();
//code
}, time);
您不应创建对Text 对象的额外引用。使用bind 方法,以便this 将指向Text 对象。喜欢-
var fadeIn = setInterval(function() {
//code
this.draw(); // <-- Check this it is `this.draw` no need for `that.draw`
//code
}.bind(this), time); //bind the object
阅读有关绑定here 的更多信息。
希望对您有所帮助。
PS:每个字符 75 毫秒,那将是神圣的每分钟 800 个字符!!!
更新 - 如果您想要可缩放的图形,您应该考虑SVG。 Canvas 是基于光栅的,而 SVG 是基于矢量的。这意味着 SVG 可以轻松调整大小,而当您调整画布大小时,画布的内容将开始像素化并且看起来很模糊。 Read more。
要调整画布内容的大小,您需要重新绘制整个画布。每当在画布上绘制某些东西时,浏览器都会绘制并忘记它。因此,如果您想更改对象的大小/位置,您需要完全清除画布并重新绘制对象。在您的情况下,您需要根据画布的大小更改ctx.font,然后更新画布,这将是一项非常繁琐的任务。