近期在做svg相关项目,很好用的东西要记下来:
1、基础知识就是根据 矩阵进行坐标转换,如下:
: 屏幕坐标 = 矩阵* svg对象坐标
2、javascript有个方法用于获取 svg对象 的转换矩阵CTM :svgObj.getScreenCTM(); 该矩阵将svg坐标转换为屏幕坐标
3、所以以上公式:已知屏幕坐标,已知矩阵,求svg对象坐标
4、如下:
5、javascript方法:矩阵.inverse() =矩阵的逆矩阵
6、代码如下:
api:
/*屏幕坐标转为svg坐标*/
coordinateTransform(screenPoint, someSvgObject) { var CTM = someSvgObject.getScreenCTM(); return screenPoint.matrixTransform(CTM.inverse()); } reportMouseCoordinates(svgElement, pageX, pageY, svgChild) { var point = svgElement.createSVGPoint(); point.x =pageX; point.y = pageY; point = coordinateTransform(point, svgChild); return point; }
调用:
bindEvent(){ this.grid.addEventListener('click',(event) => { let pageX = event.pageX; let pageY = event.pageY; let point = utils.reportMouseCoordinates(this.svg, pageX, pageY, this.grid); } }
dom:
<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet"> <defs> <pattern id="gridDot" x="0" y="0" width="1" height="1" patternUnits="userSpaceOnUse"> <path d="M0,0H1V1" stroke="#ccc" stroke-width="0.1" fill="none"></path> </pattern> <pattern id="gridBlock" x="0" y="0" width="1" height="1" patternUnits="userSpaceOnUse"> <path d="M0,0H1V1" stroke="#ccc" stroke-width="0.1" fill="none"></path> </pattern> </defs> <rect id="grid_10X10" x="0" y="0" width="100%" height="100%" fill="url(#gridDot)"> </rect> <!-- <rect id="grid_20X20" x="0" y="0" width="100%" height="100%" fill="url(#gridBlock)"> </rect> --> <!-- <text x="100" y="100" dx="20 20 20 20" dy="20" style="font-size:20px; font-family: 'Arial'">ABCDE</text> <path d="M100,0V200M0,100H200" stroke="red"></path> --> </svg>