svg中矩形旋转问题

计算中心点

/**
 * 计算中心点
 * @param {*} p 
 * @param {*} w 
 * @param {*} h 
 * @returns 
 */
function calCenterPoint(p, w, h) {
    return {
        x : p.x + w /2,
        y: p.y + h /2
    };
}
<rect xmlns="http://www.w3.org/2000/svg" x="${p.x}" y="${p.y}" width="${newWidth}" height="200" transform="rotate(${degree},${pCenter.x},${pCenter.y})" style="fill:rgb(0,122,255);stroke-width:1; stroke:rgb(0,0,0)"/>

计算旋转后的矩形起始点

这个相当于,一个点绕着中心点旋转一个角度,求解旋转后的点

/**
 * 计算旋转后的点
 * @param {*} p 原始点
 * @param {*} pCenter 旋转中心点
 * @param {*} degree 旋转度数
 * @returns 
 */
function calAfterRotationPoint(p, pCenter, degree) {
    const arc = (degree * Math.PI) / 180;
    const cosv = Math.cos(arc);
    const sinv = Math.sin(arc);

    return {
        x: ((p.x - pCenter.x) * cosv - (p.y - pCenter.y) * sinv + pCenter.x),
        y: ((p.x - pCenter.x) * sinv + (p.y - pCenter.y) * cosv + pCenter.y)
    };
}

已知旋转角度和旋转后的点,计算原始点

场景: 矩形绕原始的中心点旋转后,再调整宽高,这个时候原始点其实已经发生变化,但是旋转角度未变,我们需要计算新的原始点。

求解方程:

(x - (x + w/2)) * cosv - (y -(y + h/2))* sinv +(x + w/2) = newX;
((x - (x + w/2)) * sinv + (y - (y + h /2)) * cosv + y + h /2) = newY

化解下:

    // (x - (x + w/2)) * cosv - (y -(y + h/2))* sinv +(x + w/2) = newX;
    // - w/2 * cosv + h/2 * sinv + x + w/2 = newX
    // x = newX+ w/2 * cosv - h/2 * sinv - w/2 

    // ((x - (x + w/2)) * sinv + (y - (y + h /2)) * cosv + y + h /2) = newY
    // -w/2 * sinv - h/2 * cosv + y + h/2 = newY
    // y = newY + w/2 * sinv + h/2 * cosv - h/2

所以:

function calOriginPoint(afterRotationPoint, w, h, degree) {
    const arc = (degree * Math.PI) / 180;
    const cosv = Math.cos(arc);
    const sinv = Math.sin(arc);

    return {
        x: afterRotationPoint.x + w/2 * cosv - h/2 * sinv - w/2,
        y: afterRotationPoint.y + w/2 * sinv + h/2 * cosv - h/2
    };
}
posted @ 2021-08-19 10:26  JadePeng  阅读(516)  评论(0编辑  收藏  举报