首页 文章

拖动图像并放在SVG元素的顶部

提问于
浏览
0

我使用SVG和图像创建了两个圆圈 . 我正在尝试将图像拖动到圆圈中,而在放下图像后我能够这样做,它是不可见的 . 我怎么能把它放在圆圈上面 .

<!DOCTYPE html>
<html>
<body>
<div id="circle" >
<svg id="dest" ondrop="drop(event)" ondragover="allowDrop(event)" width="250" height="100">
<circle id="yelcirc" cx="50" cy="50" r="50" fill="yellow" />
<circle id="greencirc" cx="160" cy="50" r="50" fill="green" />
</svg>
</div>
<img id="draglogo" src="logo.gif" draggable="true" ondragstart="drag(event)" class="draggable"  ondragend="" width="105" height="73">
</body>
<script>
    function allowDrop(ev) {
         ev.preventDefault();
    }
    function drag(ev) {
         ev.dataTransfer.setData("text", ev.target.id);
    }
    function drop(ev) {
         ev.preventDefault();
         var data = ev.dataTransfer.getData("text");
         ev.target.appendChild(document.getElementById(data));
    }
</script>
</html>

1 回答

  • 0

    显然, svg 标签上未检测到 ondropondragover 事件 . 最重要的是,SVG中的图像与常规HTML中的图像语法不同 .

    这是一个简单的例子,说明如何实现你想要做的基础,当然还有一些调整,图像的位置,大小等等 . 所以我在这里做的基本上是获取原始图像属性创建SVG图像 . 您也可以在SVG标签之外放置一个常规图像,但我不确定它是否更容易定位等 .

    您还可以阅读this answer关于模拟SVG元素上的拖动事件

    注意:这仅适用于第一次拖动,即使图像在移动后仍然看起来可拖动,该函数将因为从DOM中选择 img 的方式引发错误,它已被删除,因此找不到 img 标记了 .

    <!DOCTYPE html>
    <html>
    <body>
    <div id="circle" ondrop="drop(event)" ondragover="allowDrop(event)" >
    <svg id="dest" width="250" height="100">
    <circle id="yelcirc" cx="50" cy="50" r="50" fill="yellow"  />
    <circle id="greencirc" cx="160" cy="50" r="50" fill="green" />
    </svg>
    </div>
    <img id="draglogo" src="https://placeimg.com/105/73/any" draggable="true" ondragstart="drag(event)" class="draggable"  ondragend="" width="105" height="73">
    </body>
    <script>
        function allowDrop(ev) {
             ev.preventDefault();
        }
        function drag(ev) {
             ev.dataTransfer.setData("text", ev.target.id);
        }
        function drop(ev) {
             ev.preventDefault();
             var data = ev.dataTransfer.getData("text"),
                 img = document.getElementById(data),
                 imgSrc = img.getAttribute('src'),
                 imgW = img.getAttribute('width'),
                 imgH = img.getAttribute('height'),
                 //for example you can calculate X position from event circle
                 imgX = ev.target.getAttribute('cx') - ev.target.getAttribute('r');
    
             ev.target.parentElement.innerHTML += '<image xlink:href="' + imgSrc + '" x="' + imgX + '" y="0" width="' + imgW + 'px" height="' + imgH + 'px"/>';
             img.parentNode.removeChild(img);
        }
    </script>
    </html>
    

相关问题