怎么把CanvasLoading插件嵌入你的游戏
2011-12-07 17:01 【当耐特】 阅读(3464) 评论(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();
四.插件讲解
在上面出现了两个Canvas,一个是页面当中的Canvas,用于显示游戏内容。另外一个是create出来的canvas,用于存储loading里动态信息以便写到页面当中的canvas.
原理:把内存中的动态loadingCanvas写入你的游戏Canvas当中。这其实和把视频写入canvas一个思路,也是把动态的内容写入canvas.比如HTML5实验室【二十八】—Canvas+Video打造酷炫播放体验
五.在线演示
六.同步
本文已同步更新至: