如何用JavaScript寫個炫彩小球頁面?

先看看效果:html

頁面能夠不斷自動產生大小、顏色不一的炫彩小球,一段時間會自動消失;此外,鼠標移動也能夠產生小球,也會自動消失;底部作了幾個工具按鈕,能夠控制小球大小、數量、消失速度等。 image.pngcanvas

一、小球對象瀏覽器

<script>
function Ball(x, y, r, color) {
	this.x = x || 0;
	this.y = y || 0;
	this.radius = r || 20;
	this.color = color || '#09f';
}
Ball.prototype = {
	constructor: Ball,
	stroke: function (cxt) {
		cxt.strokeStyle = this.color;
		cxt.beginPath();
		cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
		cxt.closePath();
		cxt.stroke();
	},
	fill: function (cxt) {
		cxt.fillStyle = this.color;
		cxt.beginPath();
		cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
		cxt.closePath();
		cxt.fill();
	},
	update : function( balls ){
		this.x += this.vx;
		this.y += this.vy;
		this.radius--;
		if ( this.radius < 0 ) {
			for( var i = 0; i < balls.length; i++ ){
				if( balls[i] == this ) {
					balls.splice( i, 1 );
				}
			}
			return false;
		}
		return true;
	}
}
</script>

二、產生隨機小球代碼dom

//一些初始變量
var size = 100;
var intervalTime = 50;
var rate = 1;

var ball,balls = [];
var inter;

var c=document.getElementById("myCanvas");
var oGc=c.getContext("2d");
var w=c['width'],h=c['height'];
init();
renderBall();

function init(){
	oGc.clearRect( 0, 0, w, h );
	oGc.fillStyle='#000000';
	oGc.fillRect(0,0,w,h);
}
//產生隨機顏色
var getRandomColor = function(){    
  return  '#' +    
    (function(color){    
    return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])    
      && (color.length == 6) ?  color : arguments.callee(color);    
  })('');    
} 
//小球位置隨機代碼
function getRandPos() {
    return {'x':Math.random()*w,'y':Math.random()*h};
}
//小球大小隨機代碼
function getRandDis() {
    return (1-(Math.random()*2))*rate;
}
//源源不斷產生小球
function renderBall(){
    inter = self.setInterval(function(){
        var pos = getRandPos();
        ball = new Ball( pos['x'], pos['y'], Math.random()*size, getRandomColor());
        ball.vx = getRandDis();
        ball.vy = getRandDis();
        balls.push( ball );
    }, intervalTime);
}
//使小球變得愈來愈小的代碼
( function move(){
	init();
	for( var i = 0; i < balls.length; i++ ){
		balls[i].update( balls ) && balls[i].fill( oGc );
	}
	requestAnimationFrame(move);
} )();

三、跟隨鼠標滑動產生小球工具

//監聽鼠標移動併產生小球
c.addEventListener('mousemove', function( ev ){
    var oEvent = ev || event;
    var ball = new Ball( oEvent.clientX, oEvent.clientY, 30, getRandomColor());
    ball.vx = getRandDis();
    ball.vy = getRandDis();
    balls.push( ball );
}, false );

四、控制按鈕代碼this

HTML:
<canvas id="myCanvas" width="1300" height="550"></canvas>
<div>
	<button onclick="configBall(1)">減少球</button>
	<button onclick="configBall(2)">增大球</button>
	<button onclick="configBall(3)">增長球</button>
	<button onclick="configBall(4)">減小球</button>
    <button onclick="configBall(5)">消失更快</button>
    <button onclick="configBall(6)">消失變慢</button>
</div>
JS:
function configBall(type){
	switch(type){
		case 1:
			this.size = (size <= 10 ? 10:size-10);
			break;
		case 2:
			this.size = (size >= h ? h:size+10);
			break;
		case 3:
			this.intervalTime = (intervalTime <= 5 ? 5:intervalTime-5);
			break;
        case 4:
            this.intervalTime += 5;
            break;
        case 5:
            rate = rate<<2;
            break;
        case 6:
            rate = rate>>2;
            break;
	}
    window.clearInterval(inter);
    renderBall();
}

最後,奉上所有代碼,有興趣的粘貼下來保存爲「test.html」的文件用瀏覽器打開就能看到效果。prototype

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"/>
	<title>test</title>
</head>
<script>
function Ball(x, y, r, color) {
	this.x = x || 0;
	this.y = y || 0;
	this.radius = r || 20;
	this.color = color || '#09f';
}
Ball.prototype = {
	constructor: Ball,
	stroke: function (cxt) {
		cxt.strokeStyle = this.color;
		cxt.beginPath();
		cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
		cxt.closePath();
		cxt.stroke();
	},
	fill: function (cxt) {
		cxt.fillStyle = this.color;
		cxt.beginPath();
		cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
		cxt.closePath();
		cxt.fill();
	},
	update : function( balls ){
		this.x += this.vx;
		this.y += this.vy;
		this.radius--;
		if ( this.radius < 0 ) {
			for( var i = 0; i < balls.length; i++ ){
				if( balls[i] == this ) {
					balls.splice( i, 1 );
				}
			}
			return false;
		}
		return true;
	}
}
</script>
<body>
<canvas id="myCanvas" width="1300" height="550"></canvas>
<div>
	<button onclick="configBall(1)">減少球</button>
	<button onclick="configBall(2)">增大球</button>
	<button onclick="configBall(3)">增長球</button>
	<button onclick="configBall(4)">減小球</button>
    <button onclick="configBall(5)">消失更快</button>
    <button onclick="configBall(6)">消失變慢</button>
</div>
<script>
var size = 100;
var intervalTime = 50;
var rate = 1;

var ball,balls = [];
var inter;

var c=document.getElementById("myCanvas");
var oGc=c.getContext("2d");
var w=c['width'],h=c['height'];
init();
renderBall();

function init(){
	oGc.clearRect( 0, 0, w, h );
	oGc.fillStyle='#000000';
	oGc.fillRect(0,0,w,h);
}

var getRandomColor = function(){    
  return  '#' +    
    (function(color){    
    return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])    
      && (color.length == 6) ?  color : arguments.callee(color);    
  })('');    
} 
function getRandPos() {
    return {'x':Math.random()*w,'y':Math.random()*h};
}
function getRandDis() {
    return (1-(Math.random()*2))*rate;
}

function renderBall(){
    inter = self.setInterval(function(){
        var pos = getRandPos();
        ball = new Ball( pos['x'], pos['y'], Math.random()*size, getRandomColor());
        ball.vx = getRandDis();
        ball.vy = getRandDis();
        balls.push( ball );
    }, intervalTime);
}

c.addEventListener('mousemove', function( ev ){
    var oEvent = ev || event;
    var ball = new Ball( oEvent.clientX, oEvent.clientY, 30, getRandomColor());
    ball.vx = getRandDis();
    ball.vy = getRandDis();
    balls.push( ball );
}, false );

( function move(){
	init();
	for( var i = 0; i < balls.length; i++ ){
		balls[i].update( balls ) && balls[i].fill( oGc );
	}
	requestAnimationFrame(move);
} )();

function configBall(type){
	switch(type){
		case 1:
			this.size = (size <= 10 ? 10:size-10);
			break;
		case 2:
			this.size = (size >= h ? h:size+10);
			break;
		case 3:
			this.intervalTime = (intervalTime <= 5 ? 5:intervalTime-5);
			break;
        case 4:
            this.intervalTime += 5;
            break;
        case 5:
            rate = rate<<2;
            break;
        case 6:
            rate = rate>>2;
            break;
	}
    window.clearInterval(inter);
    renderBall();
}
</script>
</body>
</html>

部分代碼參考了其餘文獻,在此感謝!code

相關文章
相關標籤/搜索