計算中心點
/**
* 計算中心點
* @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
};
}