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>

 

转载于:https://www.cnblogs.com/wangruifang/p/7517667.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值