【问题标题】:d3 SVG drag drop plus rotate with buttond3 SVG拖放加上按钮旋转
【发布时间】:2017-06-12 15:23:32
【问题描述】:

我正在尝试创建一个程序,其中可以拖放图像,但也可以在按下按钮时旋转(在被拖动后,并在其自身的轴上旋转)。我可以成功地进行图像拖放,但无法使旋转正常工作。我认为解决方案是在开始时使用“变换”、“翻译”来定位图像;并且对于拖动而不是“d3.event”但是我不确定如何做到这一点。我将 SVG 与 d3 库一起使用。我希望将我的:dragstarted、dragged 和 dragended 分开,稍后将添加更多代码。

    var svgWidth = parseInt(document.getElementById("canvas").getAttribute("width")),
    selected = null;
    canvas = d3.select('#canvas');

    canvas.append("image")
            .attr('width', 17)
            .attr('height', 59)
            .attr("x", svgWidth - 40)
            .attr("y", 100)
            .attr("xlink:href", "https://lorempixel.com/100/100/cats")
            .call(d3.drag()
                    .on("start", dragstarted)
                    .on("drag", dragged)
                    .on("end", dragended));


    canvas.append("image")
            .attr('width', 80)
            .attr('height', 38)
            .attr("x", svgWidth - 90)
            .attr("y", 200)
            .attr("xlink:href", "https://lorempixel.com/100/100/sports")
            .call(d3.drag()
                    .on("start", dragstarted)
                    .on("drag", dragged)
                    .on("end", dragended));

    function dragstarted(d){
        d3.select(this).raise().classed("active", true);
    }

    function dragged(d){
        d3.select(this)
                .attr("x", d3.event.x - parseInt(d3.select('image').attr("width")) / 2)
                .attr("y", d3.event.y - parseInt(d3.select('image').attr("height")) / 2);
    }

    function dragended(d){
        d3.select(this).classed("active", false);
        selected = this;
    }

    window.onload=function(){
        document.getElementById("rotate").addEventListener("click", function(){
            if(selected != null){
                var x = selected.getAttribute("x"),
                        y = selected.getAttribute("y");
                selected.setAttribute("transform","translate(" + x / 2 + "," + y / 2 +")" + "rotate(90)");
            }
        });
    }
<!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <link rel="stylesheet" href="styles/style.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.min.js">
        </script>
    </head>
    <body>
    <svg id="canvas" width="960px" height="500px"></svg>
    <button id="rotate">Rotate</button>
</body>
</html>

【问题讨论】:

    标签: javascript d3.js svg drag-and-drop


    【解决方案1】:

    没关系,我修好了。没有意识到不必在图像上设置 x 和 y 值即可使用 d3.event.x 和 d3.event.y 。这意味着当图像被拖动时,我可以在变换上使用这些值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      相关资源
      最近更新 更多