js fabric 學習

weixin_33724059發表於2018-06-14

參考:
https://blog.csdn.net/u014032819/article/details/77864682
http://fabricjs.com/controls-customization

需要有畫布

<canvas id="c" width="300" height="300" style="border:0px solid #aaa">
</canvas>

獲得畫布

var canvas = this.__canvas = new fabric.Canvas('c');

設定調節矩柄是否空心

fabric.Object.prototype.transparentCorners = false;

設定每個物件位置為中心座標(代替左上角座標)

fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';

設定控制矩柄可用點 (去掉四個單向縮放點)

canvas.on('after:render', function() {
    canvas.contextContainer.strokeStyle = '#555';
    canvas.forEachObject(function(obj) {
        obj['setControlVisible']('mt', false);
        obj['setControlVisible']('mb', false);
        obj['setControlVisible']('ml', false);
        obj['setControlVisible']('mr', false);
    })
});

設定矩柄色

obj['borderColor'] = 0x0;
obj['cornerColor'] = 0x0;
obj['cornerStrokeColor'] = 0x0;

新增個色塊

var rect = new fabric.Rect({
    left: 100,
    top: 50,
    width: 100,
    height: 100,
    fill: 'green',
    angle: 20,
    padding: 0
});
canvas.add(rect);

給每個元件加黑邊

canvas.on('after:render', function() {
    canvas.contextContainer.strokeStyle = '#555';
    canvas.forEachObject(function(obj) {
      var bound = obj.getBoundingRect();
      canvas.contextContainer.strokeRect(
        bound.left + 0.5,
        bound.top + 0.5,
        bound.width,
        bound.height
      );
    })
});

矩柄設定為圓形

obj['cornerStyle'] = 'circle';

新增圖片操作

fabric.Image.fromURL('img/demo.jpg', function(img) { 
    canvas.add(img.set({left:200,top:0,angle:45}).scale(.05));
});  

新增svg

fabric.loadSVGFromURL('img/demo.svg', function(objects, options) {
    var shape = fabric.util.groupSVGElements(objects, options);
    shape.scale(0.6).set({ left: 200, top: 100, angle:-45 }).setCoords();
    canvas.add(shape);
});

新增多邊形

var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120,fill:'red' });
canvas.add(path);

插入html圖片

<body>  
    <canvas id="canvas" width='800' height='800'></canvas>  
    <img src="./2.png" id="img">  
    <script type="text/javascript" src="./script.js"></script>  
</body>  
var canvas = new fabric.Canvas('canvas');//宣告畫布  
var imgElement = document.getElementById('img');//宣告我們的圖片  
var imgInstance = new fabric.Image(imgElement,{  //設定圖片在canvas中的位置和樣子  
     left:100,  
     top:100,  
     width:200,  
     height:100,  
     angle:30//設定旋轉  
});  
canvas.add(imgInstance);//加入到canvas中  

新增濾鏡

var canvas = new fabric.Canvas('canvas');  
fabric.Image.fromURL('2.jpg', function(img) {  
    //新增過濾器  
    img.filters.push(new fabric.Image.filters.Grayscale());  
    //應用過濾器並重新渲染畫布執行  
    img.applyFilters(canvas.renderAll.bind(canvas));  
    canvas.add(img);//把圖片新增到畫布上  
});  

設定顏色

new fabric.Color('#f55');  
new fabric.Color('#123123');  
new fabric.Color('356735');  
new fabric.Color('rgb(100,0,100)');  
new fabric.Color('rgba(10, 20, 30, 0.5)');  

轉換顏色

new fabric.Color('#f55').toRgb(); // "rgb(255,85,85)"  
new fabric.Color('rgb(100,100,100)').toHex(); // "646464"  
new fabric.Color('fff').toHex(); // "FFFFFF"  

設定漸變色

circle.setGradient('fill', {  
    //色標的位置  
    x1: 0,  
    y1: 0,//圓的最上沿位置  
    x2: 0,  
    y2: circle.height ,//圓的最下沿位置  
    //漸變的顏色  
    colorStops: {  
        0: '#000',  
        1: '#fff'  
    }  
}); 
colorStops: {  
        0: "red",  
        0.2: "orange",  
        0.4: "yellow",  
        0.6: "green",  
        0.8: "blue",  
        1: "purple"  
    }//彩虹的效果  

新增文字

var text = new fabric.Text('hello world', { left: 100, top: 100 });  
canvas.add(text);  

滑鼠互動

var canvas = new fabric.Canvas('canvas');  
canvas.on('mouse:down', function(options) {  
    console.log(options.e.clientX, options.e.clientY)  
})  

mouse:down :滑鼠按下時
mouse:move :滑鼠移動時
mouse:up :滑鼠抬起時
after:render :畫布重繪後
object:selected:物件被選中
object:moving:物件移動
object:rotating:物件被旋轉
object:added:物件被加入
object:removed物件被移除

選中事件

var canvas = new fabric.Canvas('canvas');  
//方形  
var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });  
rect.on('selected', function() {//選中監聽事件  
    console.log('selected a rectangle');  
});  
//圓形  
var circle = new fabric.Circle({ radius: 75, fill: 'blue' });  
circle.on('selected', function() {  
    console.log('selected a circle');  
});  
canvas.add(rect);  
canvas.add(circle); 

動畫

rect.animate('angle',360,{  
    onChange:canvas.renderAll.bind(canvas)  
})
rect.animate('left','+=100',{onChange:canvas.renderAll.bind(canvas)});  
rect.animate('angle','-=5',{onChange:canvas.renderAll.bind(canvas)});  
rect.animate('angle','-=5',{onChange:canvas.renderAll.bind(canvas),});  

複雜動畫

shape.animate('angle','-=50',{
    onChange:canvas.renderAll.bind(canvas)
    ,duration:2000
    ,easing:fabric.util.ease.easeOutBounce
});

組合物件

var group = new fabric.Group([circle, text], {  
    left: 150,  
    top: 100,  
    angle: 10  
}) ;
canvas.add(group);

操作組合內部物件

group.item(0).setFill('red');  
group.item(1).set({  
    text: 'trololo',  
    fill: 'white'  
}); 

組合中再新增物件

group.add(new fabric.Rect({  
    fill: 'blue',  
    width: 100,  
    height: 100,  
    originX: 'center',  
    originY: 'center'  
}));//不更新組合區域,可能後加入的圖形不能顯示完全  

新增並更新

group.addWithUpdate(new fabric.Rect({//更新組合區域  
  ...  
  left: group.getLeft(),  
  top: group.getTop(),  
  originX: 'center',  
  originY: 'center'  
})); 

複製一份圖形,重新渲染

var group = new fabric.Group([  
  canvas.item(0).clone(),  
  canvas.item(1).clone()  
]);  
// remove all objects and re-render  
canvas.clear().renderAll();  
// add group onto canvas  
canvas.add(group);

載入三個圖片並打包組合

fabric.Image.fromURL('1.png', function(img) {  
    var img1 = img.scale(0.1).set({  
        left: 100,  
        top: 100  
    });  
    fabric.Image.fromURL('2.png', function(img) {  
        var img2 = img.scale(0.1).set({  
            left: 175,  
            top: 175  
        });  
        fabric.Image.fromURL('1.png', function(img) {  
            var img3 = img.scale(0.1).set({ left: 250, top: 250 });  
   
            canvas.add(new fabric.Group([img1, img2, img3], { left: 200, top: 200 }));  
        });  
    });  
});  

序列化

console.log(JSON.stringify(canvas.toJSON()));  

解析序列化

var canvas = new fabric.Canvas('canvas');  
canvas.loadFromJSON( jsonStr );

轉化圖形為SVG

console.log(canvas.toSVG());  

置頂

https://www.jianshu.com/p/939974a482fe

下移:canvas.sendBackwards(canvas.getActiveObject());
上移:canvas.bringForward(canvas.getActiveObject());
置頂:canvas.bringToFront(canvas.getActiveObject());
置底:canvas.sendToBack(canvas.getActiveObject());

取消所有選擇並渲染

canvas.discardActiveObject();
canvas.requestRenderAll();

禁止多選

canvas.selection = false