SVG绘制多个圆

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            text-align: center;
        }
        svg{
            background: #ddd;
        }
    </style>
</head>
<body>
<h1>svg绘制多个圆形</h1>
<!--<svg width="500" height="400" id="s3" cx="0" cy="20" fill="#aaa"></svg>-->
<svg width="500" height="400" id="s3"></svg>
<script>
    for(var i= 0;i<30;i++){
        var c = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
        c.setAttribute('r', rn(20,100));//随机半径
        c.setAttribute('cx', rn(0,500));//随机圆心 X坐标
        c.setAttribute('cy', rn(0,400));//随机圆心 Y坐标
        c.setAttribute('fill', rc(0,255));//填充色
        c.setAttribute('fill-opacity', Math.random()); //填充透明度
        s3.appendChild(c);
        c.onclick = function(){
            var that = this;//保留this
            that.onclick = null;//放置点击两次,取消事件监听
            //标准小技巧:当前圆不能被再次点击两次
            var timer = setInterval(function(){
                   var r = that.getAttribute("r");
                   r*=1.05;//增长5%
                   that.setAttribute("r",r);
                   var p = that.getAttribute("fill-opacity");
                   p *=0.9;//减少10%
                that.setAttribute("fill-opacity",p);
                if(p<0.001){
                    clearInterval(timer);
                    timer=null;
                    s3.removeChild(that);//删除当前元素
                }
            },50)
        }
    }
    //random number ,返回指定范围的随机数
    function rn(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }
    //random color,返回指定范围内的随机颜色:rgb是0~255
    function rc(min, max) {
        var r = rn(min, max);
        var g = rn(min, max);
        var b = rn(min, max);
        return `rgb(${r}, ${g}, ${b})`;
    }
</script>
</body>
</html>

 

posted @ 2017-09-13 20:54  匿名的girl  阅读(858)  评论(0编辑  收藏  举报