SVG 鼠标点击动态绘制可拖动的圆

通过鼠标点击屏幕动态生成一个圆,同时可以通过鼠标对其进行拖动。

可在我的个人博客上进行在线演示:https://www.zhudongwork.cn/2019/01/14/SVG-%E9%BC%A0%E6%A0%87%E7%82%B9%E5%87%BB%E5%8A%A8%E6%80%81%E7%BB%98%E5%88%B6%E5%8F%AF%E6%8B%96%E5%8A%A8%E7%9A%84%E5%9C%86/

代码如下:

<!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 id="s9" width="500" height="400"></svg>
    <script>
        s9.onmousedown = function (ev) {
            var ce = ev||event;
            var cx = ce.offsetX;
            var cy = ce.offsetY;
            console.log(ev.target.id);
            if (ev.target.id!='c') createCircle(cx, cy);
        };
        function createCircle(px,py){
            var c = document.createElementNS('http://www.w3.org/2000/svg','circle');
            c.setAttribute('id',"c");
            c.setAttribute('r',"5");
            c.setAttribute('cx',px);
            c.setAttribute('cy',py);
            c.setAttribute('fill','rgb(255,0,0)');
            c.setAttribute('stroke-width','1');
            c.setAttribute('stroke','black');
            c.onmousedown = function () {
                drag(c);
            };
            c.onmouseup = function(){
                //console.log("up");
                s9.onmousemove=null;
            };
            s9.appendChild(c);
        }

        function drag(c){
            s9.onmousemove = function (ev) {
                //console.log("move");
                var e = ev||event;
                var x = e.offsetX || e.layerX;
                var y = e.offsetY || e.layerY;
                c.setAttribute('cx',''+x);
                c.setAttribute('cy',''+y);

            }

        };




    </script>


</body>
</html>

效果图 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值