一个相当无聊的东西,只是告诉你 html5 canvas 如何进行基本的使用:
<!DOCTYPE html><html lang="zh-CN"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /><title>沙加 - HTML5 - Lesson 1</title><meta name="author" content="" /></head><body><div id="content"><br /></div><script type="mce-text/javascript"> var MM = {}; MM.bind = function(fn, selfObj, var_args) { if (arguments.length > 2) { var boundArgs = Array.prototype.slice.call(arguments, 2); return function() { var newArgs = Array.prototype.slice.call(arguments); Array.prototype.unshift.apply(newArgs, boundArgs); return fn.apply(selfObj, newArgs); }; } else { return function() { return fn.apply(selfObj, arguments); }; } }; function $(id){ return document.getElementById(id); }; MM.main = function(){ var m = $("content"); //m.innerHTML = "Hello world!"; var canvas = document.createElement("CANVAS"); if(!canvas){ m.innerHTML = "Your browswer doesn't support Canvas element, please update."; return; } canvas.height = 200; canvas.width = 200; m.appendChild(canvas); //var game = new MM.PingBallGame(new MM.AbstractBrush(canvas)); var game = new MM.PingBallGame(new MM.CanvasBrush(canvas)); game.init(); //MM.setUpDebugger(); }; MM.CanvasBrush = function(canvas){ this.ctx = canvas.getContext("2d"); }; MM.CanvasBrush.prototype.drawBall = function(xx, yy , opt_radius){ var x = parseInt(xx); var y = parseInt(yy); var r = opt_radius || 5; this.ctx.beginPath(); this.ctx.moveTo(x, y); this.ctx.arc(x, y, r, 0, Math.PI*2); this.ctx.closePath(); this.ctx.fillStyle = "red"; this.ctx.fill(); }; MM.CanvasBrush.prototype.drawBackground = function(){ this.ctx.fillStyle = '#ddd'; this.ctx.fillRect(0, 0, 200, 200); }; MM.CanvasBrush.prototype.clearAll = function(){ this.ctx.clearRect(0, 0, 200, 200); }; MM.PingBallGame = function(brush){ this.brush = brush; this.ballX = 20; this.ballY = 20; this.direction = 0; this.speed = 30; //pixils per second. this.refreshRate = 10; //15 picture per second. }; MM.PingBallGame.prototype.init = function(){ //start roll the ball. this.keepRoll(); }; MM.PingBallGame.prototype.keepRoll = function(){ this.direction += Math.PI*0.20*Math.random()*((+new Date())%2 == 0?1:-1); var dx = this.speed/this.refreshRate*Math.cos(this.direction); var dy = this.speed/this.refreshRate*Math.sin(this.direction); this.speed += 10; this.ballX += dx; this.ballY += dy; if(this.ballY <= 5 || this.ballY >= 195 || this.ballX <= 5 || this.ballX >= 195){ this.direction += Math.PI; this.speed = 30; } if(this.ballX <=5){ this.ballX = 5; } if(this.ballY <=5){ this.ballY = 5; } if(this.ballX >=195){ this.ballX = 195; } if(this.ballY >=195){ this.ballY = 195; } this.brush.clearAll(); this.brush.drawBackground(); this.brush.drawBall(this.ballX, this.ballY); setTimeout(MM.bind(this.keepRoll, this), Math.floor(1000/this.refreshRate)); }; MM.main(); </script></body></html>
posted on 2011-08-27 11:16 沙加 阅读(479) 评论(0) 编辑 收藏 举报