svg拖拽和缩放
Posted midnight-visitor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了svg拖拽和缩放相关的知识,希望对你有一定的参考价值。
需求:做机房平面图,用svg实现拖拽和缩放,刚开始一头雾水,不知所措,好在皇天不负有心人........
本文重点介绍拖拽,单纯实现很简单,但是由于vue项目,机房图有很多事件,拖拽就成了难点
简单介绍下缩放实现技术要点:1.获取Svg当前缩放比例--------documen.getElementById("SVG").currentScale
放大:
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);
其他,请自行理解,有补充请留言.....
以上是关于svg拖拽和缩放的主要内容,如果未能解决你的问题,请参考以下文章