Fork me on Bolg '◡'

玩转SVG之线性转换

3月在部门组织了一场关于SVG的培训,把没有分享到博客的资料放到博文上吧,因为PPT写过了,就截图放上了,比较懒,懒得再打字了,嘿嘿~

1. 线性变换属性

2. dom转SVG的坐标点

核心代码

document.addEventListener('click', (e) => {
        let x = e.clientX;
        let y = e.clientY;
        const name = "http://www.w3.org/2000/svg"

        // 核心API
        let rect = document.createElementNS(name, 'rect')
        let svg = document.getElementById('svg')

        // svg内置API 将屏幕坐标转换为当前svg坐标 svg.createSVGMatrix();
        let rootCTM = svg.getScreenCTM();
        let pt = svg.createSVGPoint();
        pt.x = x;
        pt.y = y;
        let { x: xx, y: yy } = pt.matrixTransform(rootCTM.inverse())

        rect.setAttribute('x', xx - 5)
        rect.setAttribute('y', yy - 5)
        rect.setAttribute('width', 10)
        rect.setAttribute('height', 10)
        rect.setAttribute('fill', 'red')
        svg.appendChild(rect)
    })

posted @ 2022-04-06 10:20  webhmy  阅读(189)  评论(0编辑  收藏  举报