Fabric.js基于svg的多重剪辑

时间:2014-09-20 16:52:18

标签: javascript html5 canvas svg fabricjs

我的画布上有svg路径。我想做这样的事情: http://jsfiddle.net/tbqrn/

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

var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(10,10,150,150);
ctx.rect(180,10,200,200);
ctx.closePath();
ctx.stroke();
ctx.clip();

fabric.Image.fromURL(img01URL, function(oImg) {
oImg.scale(.25);
oImg.left = 50;
oImg.top = 100;
canvas.add(oImg);
canvas.renderAll();
});

fabric.Image.fromURL(img02URL, function(oImg) {
oImg.scale(.25);
oImg.left = 300;
oImg.top = 100;
canvas.add(oImg);
canvas.renderAll();
});

但有一点不同:离开一个区域后的图像应该立即出现在另一个区域中。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

单个画布无法做到这一点。我能想到的唯一方法是: 有两个画布有两个不同的图像,并“同步”它们之间的图像位置。你实际上必须使用两个图像。

HTML:

<canvas id="c1" width="200" height="400"></canvas>
<canvas id="c2" width="200" height="400"></canvas>

CSS:

#c1, #c2 {
    border: 1px solid #ccc;
}

#c2 {
   margin-left: 20px; 
}

.canvas-container {
    float: left;
}

JS:

var offsetLeft = 220; // #c1 width + #c2 margin-left

var canvas1 = new fabric.Canvas('c1');
var canvas2 = new fabric.Canvas('c2');

var c1Img, c2Img;

fabric.Image.fromURL(img01URL, function(oImg) {
    c1Img = oImg;

    c1Img.scale(.25);
    c1Img.left = 0;
    c1Img.top = 0;
    c1Img.hasControls = false;
    c1Img.hasRotatingPoint = false;
    canvas1.add(c1Img);
    canvas1.renderAll();
});

fabric.Image.fromURL(img01URL, function(oImg) {
    c2Img = oImg;

    c2Img.scale(.25);
    c2Img.left = -offsetLeft;
    c2Img.top = 0;
    c2Img.hasControls = false;
    c2Img.hasRotatingPoint = false;
    canvas2.add(c2Img);
    canvas2.renderAll();
});


canvas1.on('object:moving', function(e) { 
    c2Img.set({left: e.target.left -offsetLeft, top: e.target.top});
    c2Img.setCoords();
    canvas2.renderAll();
                                       });

canvas2.on('object:moving', function(e) { 
    c1Img.set({left: e.target.left + offsetLeft, top: e.target.top});
    c1Img.setCoords();
    canvas1.renderAll();
                                       });

在此测试:http://jsfiddle.net/se9sw1d8/2/