简体   繁体   中英

d3 SVG drag drop plus rotate with button

I'm attempting to create a program where an image can be dragged and dropped but also rotated at the push of a button(after being dragged, and rotated on its own axis). I can successfully make an image drag and drop but cannot get the rotate to work correctly. I think the solution would be to use a "transform","translate" for positioning the image at the start; and for the dragging instead of "d3.event" however I am unsure of how to do this. I'm using SVG with d3 library. I wish to keep my: dragstarted, dragged and dragended separate as will be adding further code later.

  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> 

Nevermind I fixed it. Didn't realise the x and y values didn't have to be set on the images to use d3.event.x and d3.event.y . Meaning I could use those values on the transform when the image was being dragged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM