美文网首页程序员
如何用JavaScript写个炫彩小球页面?

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

作者: 断翅绝尘 | 来源:发表于2018-08-21 17:02 被阅读0次

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


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>

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

相关文章

网友评论

    本文标题:如何用JavaScript写个炫彩小球页面?

    本文链接:https://www.haomeiwen.com/subject/zscjiftx.html