如何用JavaScript写个炫彩小球页面?

先看看效果:

页面可以不断自动产生大小、颜色不一的炫彩小球,一段时间会自动消失;此外,鼠标移动也可以产生小球,也会自动消失;底部做了几个工具按钮,可以控制小球大小、数量、消失速度等。 image.png

1、小球对象

<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>

2、产生随机小球代码

//一些初始变量
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);
} )();

3、跟随鼠标滑动产生小球

//监听鼠标移动并产生小球
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 );

4、控制按钮代码

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”的文件用浏览器打开就能看到效果。

<!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>

部分代码参考了其他文献,在此感谢!

转载于:https://my.oschina.net/u/180480/blog/2248983

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值