您的位置:首页 > Web前端 > HTML5

HTML5 中的 canvas 标签 实现动画效果

2009-06-15 15:00 1111 查看
看到一个兼容IE、FF的倒影效果,IE下自然是用滤镜实现了,FF下一看用的歌叫做canvas的标签,canvas倒是是什么东东呢?

地址 http://cow.neondragon.net/index.php/category/reflection

<canvas> 是一个新的 HTML 元素,这个元素在 HTML5 中被定义。这个元素通常可以被用来在 HTML 页面中通过 JavaScript 进行绘制图形、合成图像等等操作,也可以用来做一些动画。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<mce:style><!--
canvas {border:1px solid gray}

--></mce:style><style mce_bogus="1">			canvas {border:1px solid gray}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="200"></canvas>
</body>
</html>


<mce:script type="text/javascript"><!--
ctx = document.getElementById("canvas").getContext("2d");
function go() {
//		ctx.beginPath();
var b = new Ball(100, 100, 20, 2, ctx);
var b1 = new Ball(130, 100, 10, 3, ctx);
var b2 = new Ball(150, 100, 5, 4, ctx);
setInterval(function(){
ctx.clearRect(0,0,300,300)
ctx.save();
b.move()
b1.move()
b2.move();
hitTest([b,b1,b2]);
ctx.restore();
},10)
//		ctx.fill();
};

function Ball(x,y,r,s,ctx) {
this.x = x;
this.y = y;
this.r = r;
this.ctx = ctx;

this.xSpeed = -s;
this.ySpeed = 1*s;
};
Ball.prototype = {
render:function() {
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
this.ctx.fill();
},
move:function() {
//			ctx.clearRect(0,0,300,300)
//			ctx.save();
if (!this._ignore) {
if (this.x <= this.r || 300 - this.x <= this.r) {
this.xSpeed = -this.xSpeed;
this.ignore();
}

if (this.y <= this.r || 200 - this.y <= this.r) {
this.ySpeed = -this.ySpeed;
this.ignore();
}
}

this.x+=this.xSpeed;
this.y+=this.ySpeed;
this.render();
//			ctx.restore();
},
ignore : function() {
var me = this;
this._ignore = true;
setTimeout(function(){
me._ignore = false;
},20);
}
};

//检测碰撞
function hitTest(balls) {
if (balls.length<2||hitTest.ignore) return;

for (var j = 0; j < balls.length - 1; j++) {
var target = balls[j];
for (var i = j+1; i < balls.length; i++) {
var ball = balls[i];
var l = Math.sqrt(Math.pow(target.x - ball.x, 2) + Math.pow(target.y - ball.y, 2));
if (l <= (target.r + 1 * ball.r)) {
hitTest.ignore = true;
if (target.r > ball.r) {
ball.xSpeed = -ball.xSpeed;
ball.ySpeed = -ball.ySpeed;
} else {
target.xSpeed = -target.xSpeed;
target.ySpeed = -target.ySpeed;
}
setTimeout(function(){
hitTest.ignore = false;
},20)
continue;
}
}
}
//		}
}

(function() {
go();
//setInterval(go, 2000);
})();
// --></mce:script>


上面的代码FF、Chrome中有效,ie下需要加入一个excanvas.js,用VML来模拟实现。



补充资料:

HTML5 Canvas 基本语法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: