【js】canvas——Atomic-particle-motion

原子粒动
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas动画</title>
    <style>
        body{
            background-color:#000000;
        }
        canvas{
            display: block;
            position: absolute;
            top:0;
            left:0;
            -webkit-box-shadow: inset 0 0 100px #69f;
            -moz-box-shadow: inset 0 0 100px #69f;
            box-shadow: inset 0 0 100px #69f; ;
        }
    </style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
    var canvas=document.getElementById("canvas");
        cxt=canvas.getContext("2d");
        w = 500;
        h = 500;
        partical = 100;//原子数量
        particals = [];
        colors = ["#FFFF00","#FFBBFF","#346945","#FF7F00","#FF3030","#EEEE00","#98FB98","#7EC0EE","#7D26CD","#458B74"];
        canvas.width = w;
        canvas.height = h;
        aW = window.innerWidth;
        aH = window.innerHeight;
    canvas.style.left = (aW-w)/2+"px";
    canvas.style.top = (aH-h)/2+"px";
    function FC(){
        this.x = Math.round(Math.random()*w);//x
        this.y = Math.round(Math.random()*h);//y
        this.rad = Math.round(Math.random()*5)+5;//rad
        this.rgba = colors[Math.round(Math.random()*10)];
        this.vx = Math.round(Math.random()*3)-1.5;
        this.vy = Math.round(Math.random()*3)-1.5;
    }
    function draw(){
        cxt.clearRect(0,0,w,h);
        for(var i=0;i<partical;i++){
            var p = particals[i];
            for(var j=0;j<partical;j++){
                var pp = particals[j];
                if(p.rgba == pp.rgba && findDistance(p,pp)<50){
                    cxt.strokeStyle = p.rgba;
                    cxt.moveTo(p.x, p.y);
                    cxt.lineTo(pp.x,pp.y);
                    cxt.stroke();
                }
            }
            cxt.beginPath();
            cxt.fillStyle= p.rgba;
            cxt.arc(p.x, p.y, p.rad,0,Math.PI*2,true);
            cxt.fill();
            cxt.closePath();
            cxt.beginPath();
            cxt.strokeStyle= p.rgba;
            cxt.arc(p.x, p.y, p.rad+20,0,Math.PI*2,true);
            cxt.stroke();
            cxt.closePath();
        }
        upData()
    }
    function upData(){
        for(var i=0;i<partical;i++){
            var p = particals[i];
            p.x += p.vx;
            p.y += p.vy;
            if(p.x>w)p.x=0;
            if(p.x<0)p.x=w;
            if(p.y>h)p.y=0;
            if(p.y<0)p.y=h;
        } 
   } 
   function findDistance(p1,p2){
        return Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y,2));
    }
    (function int(){
        for(var i=0;i<partical;i++){
            particals.push(new FC)
        }
    })();
setInterval(draw,15)
</script>
</body>
</html>

 

 
posted @ 2016-04-18 13:53  宿命1016  阅读(244)  评论(0编辑  收藏  举报