我想不通你的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);
};
}
,因爲它創造的方法,每次你不應該通過構造方法添加到對象該對象被實例化。而是將方法添加到對象的原型,這樣,它們將只創建一次,並將由所有實例共享。 Like-
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);
}
此外,我發現你正在創建額外的變量來指向一些對象。 Like -
var that = this;
var fadeIn = setInterval(function() {
//code
that.draw();
//code
}, time);
您不應該爲Text
對象創建額外的引用。使用bind
方法,以便this
將指向Text
對象。 Like-
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。畫布是基於柵格的,而SVG是基於矢量的。這意味着SVG可以輕鬆調整大小,而當您調整畫布的大小時,畫布的內容將開始像素化並顯得模糊。 Read more。
要調整畫布的內容,您需要重新繪製整個畫布。只要在畫布上繪製東西,瀏覽器就會繪製並忘記它。所以如果你想改變對象的大小/位置,你需要完全清除畫布並重繪對象。在你的情況下,你需要根據畫布的大小更改ctx.font
,然後更新畫布,這將是一個非常乏味的任務。
+1 for _solution with NO plugins!標準的JavaScript和HTML5 Canvas!_。我喜歡。但是你的代碼評論很差。目前還不清楚'typeText'方法需要什麼參數以及'baseObjects'實際是什麼。 – ShuklaSannidhya 2013-03-31 12:54:28
你可以告訴你如何調用'typeText',你傳遞的是什麼參數? – ShuklaSannidhya 2013-03-31 12:58:48
'baseObjects'是畫布上所有對象的數組(用於重繪)。 從Text對象調用'typeText()'。所以我會做'var text = new Text();'然後調用'text.typeText(baseObjects,20);' – Jamesking56 2013-04-01 09:40:42