在svg文间画图过程中放大缩小图片后,坐标偏移问题

http://blog.csdn.net/qingcai20071141/article/details/6257184

//鼠标坐标:在SVG经过缩放、偏移、ViewBox转换后,鼠标坐标值
var mouseCoord = {
x : 0.,
y : 0.
};
//用户坐标:相对于原始SVG,坐标位置
var userCoord = {
x : 0.,
y : 0.
};
var cRadius = 4.; //半径

var svgDocument = null;
var svgRoot = null;

//获取鼠标事件相关的SVG Document
function getSVGDocument(evt)
{
var target = evt.target;
var parent = target.parentNode;
svgDocument = parent.getOwnerDocument();
svgRoot = svgDocument.documentElement;
}

//计算坐标位置:包括用户坐标、鼠标坐标
function getCoords(evt)
{
var x_trans = 0.; //X偏移
var y_trans = 0.; //Y偏移
var x_scale = 1.; //ViewBox导致的X缩放比例
var y_scale = 1.; //ViewBox导致的Y缩放比例
var scale = 1.; //缩放比例
var trans = null;
var viewbox = null;

getSVGDocument(evt);

scale = svgRoot.currentScale; //获取当前缩放比例
trans = svgRoot.currentTranslate; //获取当前偏移
//获取SVG的当前viewBox
viewbox = svgRoot.getAttributeNS(null, "viewBox"); //获取ViewBox属性

//获取用户坐标:原始SVG的坐标位置
userCoord.x = evt.getClientX();
userCoord.y = evt.getClientY();

//计算偏移、缩放等
x_trans = ( 0.0 - trans.x ) / scale;
y_trans = ( 0.0 - trans.y ) / scale;
// Now that we have moved the rectangle's corner to the
// upper-left position, let's scale the rectangle to fit
// the current view. X and Y scales are maintained seperately
// to handle possible anamorphic scaling from the viewBox
zoom = scale;
x_scale = 1.0 / scale;
y_scale = 1.0 / scale;
if ( viewbox ) {
// We have a viewBox so, update our translation and scale
// to take the viewBox into account
// Break the viewBox parameters into an array to make life easier
var params = viewbox.split(//s+/);
// Determine the scaling from the viewBox
// Note that these calculations assume that the outermost
// SVG element has height and width attributes set to 100%.
var h_scale = 1.0 / parseFloat(params[2]) * window.innerWidth;
var v_scale = 1.0 / parseFloat(params[3]) * window.innerHeight;
// Update our previously calculated transform
x_trans = x_trans / h_scale + parseFloat(params[0]);
y_trans = y_trans / v_scale + parseFloat(params[1]);
x_scale = x_scale / h_scale;
y_scale = y_scale / v_scale;
}
//根据用户坐标、偏移量、缩放等计算鼠标坐标
mouseCoord.x = userCoord.x * x_scale + x_trans;
mouseCoord.y = userCoord.y * y_scale + y_trans;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值