标签:调用 rect console 难点 javascrip style lis 简单 class
本文重点介绍拖拽,单纯实现很简单,但是由于vue项目,机房图有很多事件,拖拽就成了难点
放大:
documen.getElementById("SVG").currentScale = documen.getElementById("SVG").currentScale1.5
缩小:
documen.getElementById("SVG").currentScale = documen.getElementById("SVG").currentScale0.5
要点介绍:
1.这个请自行学习下Matrix矩阵: transform="matrix(1 0 0 1 0 0)"
2.想拖拽谁,就在谁那里调用 : onmousedown="selectElement(evt)"
<!DOCTYPE HTML>
<html lang="">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>
<style>
<style>
.draggable {
cursor: move;
}
svg{background:pink;}
</style>
</style>
<body>
<svg
transform="matrix(1 0 0 1 0 0)"
onmousedown="selectElement(evt)"
viewBox="0 0 400 300"
width="400" height="300" xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect class="draggable"
transform="matrix(1 0 0 1 0 0)"
onmousedown="selectElement(evt)"
x="0" y="0"
width="80" height="80"
fill="blue"/>
</svg>
</body>
<script type="text/javascript">
var selectedElement = 0;
var currentX = 0;
var currentY = 0;
var currentMatrix = 0;
function selectElement(evt) {
selectedElement = evt.target;
currentX = evt.clientX;
currentY = evt.clientY;
console.log(currentX,currentY);
currentMatrix = selectedElement.getAttributeNS(null, "transform").slice(7,-1).split(‘ ‘);
for(var i=0; i<currentMatrix.length; i++) {
currentMatrix[i] = parseFloat(currentMatrix[i]);
}
selectedElement.setAttributeNS(null, "onmouseout", "deselectElement(evt)");
selectedElement.setAttributeNS(null, "onmouseup", "deselectElement(evt)");
selectedElement.setAttributeNS(null, "onmousemove", "moveElement(evt)");
}
function moveElement(evt){
console.log(evt.clientX,evt.clientY);
console.log(currentX,currentY);
dx = evt.clientX - currentX;
dy = evt.clientY - currentY;
currentMatrix[4] += dx;
currentMatrix[5] += dy;
newMatrix = "matrix(" + currentMatrix.join(‘ ‘) + ")";
selectedElement.setAttributeNS(null, "transform", newMatrix);
currentX = evt.clientX;
currentY = evt.clientY;
}
function deselectElement(evt){
if(selectedElement != 0){
selectedElement.removeAttributeNS(null, "onmousemove");
selectedElement.removeAttributeNS(null, "onmouseout");
selectedElement.removeAttributeNS(null, "onmouseup");
selectedElement = 0;
}
}
</script>
</html>
嵌入vue项目,貌似selectedElement.setAttributeNS(null, "", "");不好使
1.请尝试绑定方法:
selectedElement.addEventListener("mousemove", this.moveElement(event), false);
2.记得执行完解绑:
selectedElement.addEventListener("mouseup", (event) => {
selectedElement.removeEventListener("mousemove", this.moveElement(event), false);
}, false);
标签:调用 rect console 难点 javascrip style lis 简单 class
原文地址:https://www.cnblogs.com/midnight-visitor/p/10150547.html