如何使用Fabric.js创建径向渐变

问题描述

我似乎找不到最新的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();
}

解决方法

阅读画布渐变的规格后,我能够提出正确的设置来设置画布以及对象的径向渐变。更新了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
        }
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...