【问题标题】:How to create a Radial Gradient using Fabric.js如何使用 Fabric.js 创建径向渐变
【发布时间】:2020-09-14 02:21:36
【问题描述】:

我似乎无法为最新的 Fabric (4.1) 找到一个很好的例子,在整个画布上或在像 Rect 这样的对象上设置径向渐变。

我对线性渐变没有任何问题,但是为径向(我只想在中心)正确定位却让我望而却步。这是is a codepen 我尝试过的。

JS:

let canvas = new fabric.Canvas("c", {
    isDrawingMode: false
});

let colorStops; 
let angle = 180;

const shapeColorStops = {};
var anglePI = (-parseInt(angle, 10)) * (Math.PI / 180);

const setBackgroundGradient = (e) => {
    let coords;
    let type = e.target.id;

    if (type == 'radial') {
        console.log('trying to set radial gradient')
        coords = {
            r1: canvas.width/2,
            r2: 0,
            x1: canvas.width/2,
            y1: canvas.height/2,
          //  x2: 0,
          //  y2: 0
        }
    }
    else {
        console.log('trying to set linear gradient')
        coords = {
            x1: (Math.round(50 + Math.sin(anglePI) * 50) * canvas.width) / 100,
            y1: (Math.round(50 + Math.cos(anglePI) * 50) * canvas.height) / 100,
            x2: (Math.round(50 + Math.sin(anglePI + Math.PI) * 50) * canvas.width) / 100,
            y2: (Math.round(50 + Math.cos(anglePI + Math.PI) * 50) * canvas.height) / 100,
        }
    }
    var grad = new fabric.Gradient({
        type: type,
        coords: coords,
        colorStops: [
        {
            color: 'rgb(166,111,213)',
            offset: 0,
        },
        {    
            color: '#200772',
            offset: 1,
        }
        ]});
    canvas.setBackgroundColor(grad);
    canvas.renderAll();
}

【问题讨论】:

    标签: canvas fabricjs gradient radial-gradients


    【解决方案1】:

    在阅读了画布渐变的规范后,我能够提出正确的设置来为画布和对象设置径向渐变。更新codepen is here

    这是使径向渐变起作用的部分:

        if (!el) el =  canvas;
        let coords;
        let size = {width: el.width, height: el.height}
        let num = size.height/2;
        let radius = num + size.width/4;
    
        
        if (type == 'radial') {
            console.log('trying to set radial gradient, size is '+JSON.stringify(size))
           // the numbers for my canvas are  width="1920" height="1080"
            coords = {
            r1: radius,
            r2: size.width *.05,
           
            x1: size.width/2,
            y1: size.height/2,
            
            x2: size.width/2,
            y2: size.height/2
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多