0
我正在嘗試創建一個程序,可以拖放圖像,也可以在按下按鈕(拖動並旋轉自己的軸後)時進行旋轉。我可以成功拖放圖像,但無法正確旋轉。我認爲解決方案將是在開始時使用「變換」,「翻譯」來定位圖像;和拖動而不是「d3.event」,但我不確定如何做到這一點。我正在用d3庫使用SVG。我希望將我的:dragstarted,dragged和dragended分開,以後再添加更多代碼。d3 SVG拖放加旋轉按鈕
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>