怎么把CanvasLoading插件嵌入你的游戲
2011-12-07 17:01 【當(dāng)耐特】 閱讀(3486) 評論(3) 收藏 舉報一.簡介
CanvasLoading插件適用于任何基于Canvas游戲的loading過程展示。
二.插件源碼
Loading = function (text, fontSize,baseFontSize, color, position, interval, font, bolder) { this.text = text; this.fontSize = fontSize; this.baseFontSize=baseFontSize; this.color = color; this.position = position; this.interval = interval; this.font = font; this.bolder = bolder; return this.init(); } Loading.prototype.init = function () { var text = []; var _this = this; var words = _this.text.split(""); for (i in words) { text.push({ "text": words[i], "fontSize": _this.fontSize, "baseFontSize":_this.baseFontSize, "color": _this.color, "position": new Vector2(_this.position.x + i * _this.interval, _this.position.y), "font": _this.font, "bolder":_this.bolder }); } return text; } Vector2 = function (x, y) { this.x = x || 0; this.y = y || 0; }; var loading = new Loading("this is loading canvas", 30, 30,"#ffffff", new Vector2(20, 80), 15, "宋體", "bolder"); var loadingCanvas = document.createElement('canvas'); loadingCanvas.width = 420; loadingCanvas.height = 100; var cxt = loadingCanvas.getContext("2d"); cxt.fillStyle = loading[0].color; function drawLoading() { for (i in loading) { cxt.font = loading[i].bolder + " " + loading[i].fontSize + "px " + loading[i].font; cxt.fillText(loading[i].text, loading[i].position.x, loading[i].position.y); } } var currentMap = 0; function changeFontSize() { if (currentMap > 895) currentMap = 0; currentMap += 5; if (parseInt(currentMap / 40) <= loading.length - 1) { loading[parseInt(currentMap / 40)].fontSize = 2 * loading[0].baseFontSize - currentMap % 40; } if (parseInt(currentMap / 40) + 1 <= loading.length - 1) { loading[parseInt(currentMap / 40) + 1].fontSize = currentMap % 40 + loading[0].baseFontSize; } } function draw() { cxt.clearRect(0, 0, loadingCanvas.width, loadingCanvas.height); drawLoading(); changeFontSize(); } setInterval(draw, 10);
三.插件使用
var canvas = document.getElementById("myCanvas"); var context = canvas.getContext('2d'); context.font = "bolder 40px 宋體"; context.fillStyle = "#ffffff"; var gameLoadingAsync = eval(Jscex.compile("async", function () { while (true) { context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(loadingCanvas, 0, 0); context.fillText("this is game canvas!", 10, 38); $await(Jscex.Async.sleep(10)); } })) gameLoadingAsync().start();
四.插件講解
在上面出現(xiàn)了兩個Canvas,一個是頁面當(dāng)中的Canvas,用于顯示游戲內(nèi)容。另外一個是create出來的canvas,用于存儲loading里動態(tài)信息以便寫到頁面當(dāng)中的canvas.
原理:把內(nèi)存中的動態(tài)loadingCanvas寫入你的游戲Canvas當(dāng)中。這其實和把視頻寫入canvas一個思路,也是把動態(tài)的內(nèi)容寫入canvas.比如HTML5實驗室【二十八】—Canvas+Video打造酷炫播放體驗
五.在線演示
六.同步
本文已同步更新至:

浙公網(wǎng)安備 33010602011771號