canvas线性渐变获取度数:根据渐变线型坐标x1,x2,y1,y2计算角度

/**
     * 根据 object 的 fill.coords 来计算 angle 分四个象限
     * @param fabricObject
     * @returns {number}
     */
    static getLinearGradientAngle(fabricObject) {
        fabricObject = _.cloneDeep(fabricObject)
        let angle = 0
        if (fabricObject.fill.colorStops) {
            //元素中心点坐标
            let cPos = {
                x: fabricObject.width / 2,
                y: fabricObject.height / 2
            }
            //渐变坐标
            let gPos = {
                x1: fabricObject.fill.coords.x1,
                x2: fabricObject.fill.coords.x2,
                y1: fabricObject.fill.coords.y1,
                y2: fabricObject.fill.coords.y2
            }

            if (this.isFirstQuadrant(gPos, cPos)) {//第一象限
                angle = Math.atan((gPos.x1 - cPos.x) / (cPos.y + (-gPos.y1))) / (Math.PI / 180)
            } else if (this.isSecondQuadrant(gPos, cPos)) {//第二象限
                angle = Math.atan((gPos.y1 - cPos.y) / (gPos.x1 - cPos.x)) / (Math.PI / 180) + 90
            } else if (this.isThirdQuadrant(gPos, cPos)) {//第三象限
                angle = Math.atan((gPos.x2 - cPos.x) / (gPos.y1 - cPos.y)) / (Math.PI / 180) + 180
            } else if (this.isFourthQuadrant(gPos, cPos)) {//第四象限
                angle = Math.atan((gPos.y2 - cPos.y) / (gPos.x2 - cPos.x)) / (Math.PI / 180) + 270
            }
        }
        return Math.round(angle)
    }

    /**
     * 判断坐标是否为第一象限内
     * @param gPos
     * @param cPos
     * @returns {boolean}
     */
    static isFirstQuadrant(gPos, cPos) {
        return (gPos.x1 > cPos.x && gPos.y1 < 0 && gPos.x2 < cPos.x && gPos.y2 > (cPos.y * 2)) ||
            (gPos.x1 > (cPos.x * 2) && gPos.y1 < cPos.y && gPos.x2 < 0 && gPos.y2 > cPos.y);
    }

    /**
     * 判断坐标是否为第二象限
     * @param gPos
     * @param cPos
     * @returns {boolean}
     */
    static isSecondQuadrant(gPos, cPos) {
        return (gPos.x1 > (cPos.x * 2) && gPos.y1 > cPos.y && gPos.x2 < 0 && gPos.y2 < cPos.y) ||
            (gPos.x1 > cPos.x && gPos.y1 > (cPos.y * 2) && gPos.x2 < cPos.x && gPos.y2 < 0);
    }

    /**
     * 判断坐标是否为第三象限
     * @param gPos
     * @param cPos
     * @returns {boolean}
     */
    static isThirdQuadrant(gPos, cPos) {
        return (gPos.x1 < cPos.x && gPos.y1 > (cPos.y * 2) && gPos.x2 > cPos.x && gPos.y2 < 0) ||
            (gPos.x1 < 0 && gPos.y1 > cPos.y && gPos.x2 > cPos.x * 2 && gPos.y2 < cPos.y);
    }

    /**
     * 判断坐标是否为第四象限
     * @param gPos
     * @param cPos
     * @returns {boolean}
     */
    static isFourthQuadrant(gPos, cPos) {
        return (gPos.x1 < 0 && gPos.y1 < cPos.y && gPos.x2 > cPos.x * 2 && gPos.y2 > cPos.y) ||
            (gPos.x1 < cPos.x && gPos.y1 < 0 && gPos.x2 > cPos.x && gPos.y2 > cPos.y * 2);
    }

上一篇:RectMask2D裁剪Canvas无效问题


下一篇:tml2canvas.js+jsPDF.js 实现div转pdf文件