新手关于JS操作SVG的问题,如何以鼠标为中心缩放SVG?

心有玲兮一点通 2015-04-17 03:43:47
如何以鼠标为中心缩放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>
...全文
825 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
douyabanban 2016-09-29
  • 打赏
  • 举报
回复
先找出真实坐标和视区坐标的转换关系,再将缩放后往反方向平移视区坐标的差值。
hwqDqwh 2015-12-15
  • 打赏
  • 举报
回复
楼主解决问题了吗,同遇到问题...
  • 打赏
  • 举报
回复
没人吗,哎真难

87,908

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧