//鼠標坐標:在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; }