我尝试创建一个程序,可以拖放图像,但也可以通过按下按钮进行旋转(拖动后,在自己的轴上旋转)。我可以成功地拖放图像,但无法使旋转正常工作。我认为解决方案是使用"转换","翻译"用于在开始时定位图像;并且用于拖动而不是" d3.event"但我不确定如何做到这一点。我使用SVG和d3库。我希望保留我的:dragstarted,dragged and 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>
&#13;
答案 0 :(得分:0)
没关系我修好了。没有意识到不必在图像上设置x和y值以使用d3.event.x和d3.event.y。这意味着我可以在拖动图像时在变换上使用这些值。