HTML5 Canvas彩色小球碰撞運動特效是一款基於canvas加面向對象制作的運動小球動畫特效。
效果展示
效果圖如下:
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas彩色小球碰撞運動特效 - 何問起</title>
<base target="_blank" />
<style>
#hovertreeball {
border: 1px dashed #999;
box-shadow: 0px 4px 40px #233;
background: black;
}
.hovertreeinfo{text-align:center;}
a{color:blue;}
</style>
</head>
<body>
<div class="hovertreeinfo" >
提示:可以點擊按鈕改變背景顏色<br />
<canvas id="hovertreeball" width="800" height="600"></canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById("hovertreeball");
var context = canvas.getContext("2d");
var maxWidth = canvas.width;
var maxHeight = canvas.height;
var colors = ["#33B5E5", "#0099CC", "#AA66CC", "#9933CC", "#99CC00", "#669900", "#FFBB33", "#FF8800", "#FF4444", "#CC0000"]
//隨機數
function random(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
//構造函數
function Ball() {
this.a = true;
this.b = true;
this.r = random(10, 30);
this.ballColor = { color: colors[Math.floor(Math.random() * colors.length)] }
this.vx = random(30, maxWidth - 30);
this.vy = random(30, maxHeight - 30);
this.ispeed = random(1, 10);
this.ispeed2 = random(1, 10);
}
// 面向對象
Ball.prototype.moveBall = function () {
context.beginPath();
if (this.a) {
this.vx += this.ispeed;
if (this.vx >= maxWidth - this.r) {
this.a = false;
}
} else {
this.vx -= this.ispeed;
if (this.vx <= this.r) {
this.a = true;
}
}
if (this.b) {
this.vy += this.ispeed2;
if (this.vy >= maxHeight - this.r) {
this.b = false;
}
} else {
this.vy -= this.ispeed2;
if (this.vy <= this.r) {
this.b = true;
}
}
context.fillStyle = this.ballColor.color;
context.arc(this.vx, this.vy, this.r, 0, Math.PI * 2, false);
context.fill();
}
var Aball = [];
for (var i = 0; i < 100; i++) {
Aball[i] = new Ball();
}
setInterval(function () {
context.clearRect(0, 0, canvas.width, canvas.height)
for (var i = 0; i < 100; i++) {
Aball[i].moveBall();
}
}, 30)
function hovertreecolor() {
if (canvas.style.backgroundColor != "white") {
canvas.style.backgroundColor = "white";
}
else {
canvas.style.backgroundColor = "black";
}
}
</script>
<div style="text-align:center;margin:10px 0; font:normal 14px/24px 'MicroSoft YaHei';">
<button id="hovertreechange">改變背景顏色</button>
<p>適用浏覽器:360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗. 不支持IE8及以下浏覽器。</p>
<p>來源:<a href="http://hovertree.com/" target="_blank">何問起</a> <a href="http://hovertree.com/menu/texiao/">網頁特效</a>
<a href="http://hovertree.com/h/bjaf/mll8cpr3.htm">代碼說明</a></p>
</div>
<script>
document.getElementById("hover" + "treechange").addEventListener("click", hovertreecolor)
</script>
</body>
</html>