Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var imgURL = 'http://fabricjs.com/lib/pug.jpg';
- var clipYellowRect = null;
- var clipRedRect = null;
- var pug = null;
- var canvas = new fabric.Canvas('c');
- // insert image into canvas
- var pugImg = new Image();
- pugImg.onload = function (img) {
- pug = new fabric.Image(pugImg, {
- angle: 0,
- width: 500,
- height: 500,
- left: 100,
- top: 50,
- scaleX: 0.5,
- scaleY: 0.5,
- clipName: 'pug',
- });
- canvas.add(pug);
- };
- pugImg.src = imgURL;
- //draw yellow rectangle
- $('#btnYellowRect').on('click', function(){
- clipYellowRect = new fabric.Rect({
- originX: 'left',
- originY: 'top',
- left: 120,
- top: 60,
- width: 200,
- height: 200,
- fill: 'rgba(255,255,0,0.5)',
- strokeWidth: 0,
- selectable: false
- });
- canvas.add(clipYellowRect);
- });
- //draw red rectangle
- $('#btnRedRect').on('click', function(){
- clipRedRect = new fabric.Rect({
- originX: 'left',
- originY: 'top',
- left: 90,
- top: 120,
- width: 100,
- height: 100,
- strokeWidth: 3,
- fill: 'transparent',
- stroke: 'rgba(255,0,0,1)', /* use transparent for no fill */
- strokeWidth: 0,
- selectable: false
- });
- canvas.add(clipRedRect);
- });
- //clip
- $('#btnClip').on('click', function(){
- var yellowRectRegion = getRegion(clipYellowRect);
- var redRectRegion = getRegion(clipRedRect);
- //determine inersection
- var intersectResult = PolyBool.intersect({
- regions: [yellowRectRegion],
- inverted: false
- }, {
- regions: [redRectRegion],
- inverted: false
- });
- //generate clipping path
- var xorResult = PolyBool.xor({
- regions: [yellowRectRegion],
- inverted: false
- }, {
- regions: intersectResult.regions,
- inverted: false
- });
- clipImage(xorResult.regions[0]);
- });
- //prepare data for clipping library
- function getRegion(rect){
- return [[rect.left, rect.top],
- [rect.left + rect.width, rect.top],
- [rect.left + rect.width, rect.top + rect.height],
- [rect.left, rect.top + rect.height]]
- }
- function clipImage(points){
- //actual clipping
- pug.clipTo = function (ctx) {
- var scaleXTo1 = (1 / pug.scaleX);
- var scaleYTo1 = (1 / pug.scaleY);
- ctx.save();
- var ctxLeft = -( pug.width / 2 );
- var ctxTop = -( pug.height / 2 );
- ctx.translate( ctxLeft, ctxTop );
- ctx.scale(scaleXTo1, scaleYTo1);
- ctx.beginPath();
- console.log(points)
- ctx.moveTo(points[0][0] - pug.oCoords.tl.x, points[0][1] - pug.oCoords.tl.y);
- for (var i=1; i < points.length; i++){
- ctx.lineTo(points[i][0] - pug.oCoords.tl.x, points[i][1] - pug.oCoords.tl.y);
- }
- ctx.closePath();
- ctx.restore();
- };
- clipYellowRect.remove();
- clipRedRect.remove();
- canvas.renderAll();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement