新手关于JS操作SVG的问题,如何以鼠标为中心缩放SVG?
如何以鼠标为中心缩放SVG(就像百度地图样的效果);
已经用jQuery实现了SVG的鼠标滚轮缩放,现在怎么以鼠标为中心缩放?默认是左上角!
代码实现了鼠标滚轮缩放g标签,红色部分是我百度后自己写的鼠标中心缩放,可是不对,求解
给思路也行:
<div > < svg > <g> <元素块> </g> < /svg> </ div>
如何让G标签以鼠标为中心缩放
<style type="text/css">
#old{width:400px;height:400px; border:blue 1px solid;position:absolute;margin:50px 50px;}
#svg{width:100%;height:100%; border:red 1px solid;position:absolute;}
</style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
this.proportion=1;
this.mouseleft;
this.mouseleft;
//oX,oY是svg距离父元素(div)的偏移量,这里固定为0;
this.oX=0;
this.oY=0;
var me = this;
//移动鼠标,获得在DIV中的坐标
$("#old").mousemove(function(e) {
var e = e || window.event;
me.mouseleft = e.offsetX ? e.offsetX
: e.originalEvent.layerX;
me.mousetop = e.offsetY ? e.offsetY
: e.originalEvent.layerY;
});
//鼠标滚轮事件
this.mouseWheelHandler = function(event) {
this.getCount = function(delta, num) {
if (delta > 0) {
num = num * 1.15;
} else {
num = num / 1.15;
}
return num;
};
var delta = 0;
if (!event)
event = window.event;
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
alert(delta);
} else if (event.detail) {
delta = -event.detail / 3;
}
;
this.proportion = this.getCount(delta, this.proportion);
//-----------------------鼠标焦点缩放--------------------------
this.centerOffsetX = (this.proportion - 1) * this.mouseleft;
this.centerOffsetY = (this.proportion - 1) * this.mousetop;
$("#g").attr({
"transform" : "translate(" + (this.oX -this.centerOffsetX) + "," + (this.oY -this.centerOffsetY)+ "),scale(" + this.proportion + ")"
});
//-----------------------鼠标焦点缩放--------------------------
//$("#g").attr("transform" ,"scale("+this.proportion + ")");
};
var me = this;
//绑定鼠标滚轮事件
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', function(event) {
me.mouseWheelHandler(event, me);
}, false);
}
window.onmousewheel = document.onmousewheel = this.mouseWheel;
})
</script>
</head>
<body>
<div id="old">
<svg id="svg">
<g id="g" >
<rect id="1" x="0" width="40" height="40" style="fill:black;"/>
<rect id="2" x="40" width="40" height="40" style="fill:red;"/>
<rect id="3" x="80" width="40" height="40" style="fill:green;"/>
<rect id="4" x="0" y="40" width="40" height="40" style="fill:blue;"/>
<rect id="5" x="40" y="40" width="40" height="40" style="fill:yellow;"/>
<rect id="6" x="80" y="40" width="40" height="40" style="fill:pink;"/>
</g>
</svg>
</div>
</body>