单击按钮,使用fabricjs为渐变赋予形状

时间:2013-09-20 10:02:29

标签: javascript jquery html canvas fabricjs

我想为fabric.js中的形状赋予渐变样式,我想为所有形状编写常用的添加渐变方法,选择对象并单击提交按钮,它应该将填充更改为渐变。

小提琴:: http://jsfiddle.net/jdFet/1/

请检查以上小提琴,

代码::

 var canvas;

$(function () {
    canvas = window.__canvas = new fabric.Canvas('canvas');
    canvas.backgroundColor = '#FFFFFF';
    var circle = new fabric.Circle({
        left: 100,
        top: 100,
        radius: 100
    });

    circle.setGradient('fill', 
                       { type:'linear',
                        x1: 0, 
                        y1: 0, 
                        x2: 0, 
                        y2: circle.height,
                        colorStops: { 0 : 'rgba(0,255,0,1)', 1 : 'rgba(0,0,255,1)'} });
    canvas.add(circle);
    console.log('Gradient', circle.fill);
});

1 个答案:

答案 0 :(得分:1)

从你的jsfiddle,我得到了这个 - http://jsfiddle.net/hellomaya/jdFet/6/ 选择所有形状,然后更改其渐变。

if (!obj) {
        obj = canvas.getActiveGroup();
        if (!obj) {
            return;
        }
        console.log (obj._objects);

        var objects = obj.getObjects();
        for (i in objects) {
            objects[i].setGradient('fill', {
                type: 'linear',
                x1: 0,
                y1: 0,
                x2: 0,
                y2: objects[i].height,
                colorStops: {
                    0: 'black',
                    1: 'red'
                }
            });
        }
        canvas.renderAll();
        return;
    }