前段时间做了一个需求,svg元素渐变,支持给svg元素设置线性渐变,径向渐变,设置渐变角度;
测试的过程中,发现一个问题:
当我把角度设置到90度时,线性渐变的显示就会有问题
说明算的缩放不对,只显示了部分
那我们就需要根据元素的宽,高,对角线,去算对应的缩放值
const ratio = newHeight / newWidth
// 对角线
const maxDiagonal = Math.sqrt((newWidth / 2) ** 2 + (newHeight / 2) ** 2)
// 对角线对应的角度
const maxDeg = Math.round(Math.atan(ratio) * 180 / Math.PI)
// 旋转角度
const rotateDeg = Math.min(Math.abs(rotateValue % 180), 180 - Math.abs(rotateValue % 180))
// 计算对边,即新的宽
const newDegWidth = maxDiagonal * Math.cos(Math.abs(maxDeg - rotateDeg) * Math.PI / 180)
const scaleValue = newDegWidth / (newWidth / 2)
gradientTransform = `rotate(${rotateValue}) translate(-${translateX}, -${translateY}) scale(${scaleValue})`
算好之后运行,发现还是没生效,为啥呢?难道是算错了?
看了半天,尝试设置了下transform-origin:center;
试了下,OK,可以了。