• svg 实践之屏幕坐标与svg元素坐标转换


    近期在做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>
  • 相关阅读:
    IIS代理
    NODEJS
    js图表插件
    注册nodejs程序为windows服务
    中断子系统7_中断出口处理
    Leetcode: Sort List
    jquery 鼠标经过放大图片
    在Tomcat上运行ADF Essentials应用
    简谈HTML5与APP技术应用
    Boost的Serialization和SmartPoint搭配使用
  • 原文地址:https://www.cnblogs.com/smedas/p/12482789.html
Copyright © 2020-2023  润新知