Fabricjs mask object with transformation

后端 未结 2 1355
别跟我提以往
别跟我提以往 2021-02-19 04:03

I\'m trying to mask an object using Fabric.js free drawing brush. It works fine if the object is in its default position and without any transformations. But once I

2条回答
  •  礼貌的吻别
    2021-02-19 04:38

    I implement an exemple with some transformations (scaleX,scaleY,left,top). I'm strugle to find a solution when the inital object have an angle different than 0. For the current solution I need it to divide the maskscale with the object scale and also adjust the positions.

    let canvas = new fabric.Canvas("canvas", {
        backgroundColor: "lightgray",
        width: 1280,
        height: 720,
        preserveObjectStacking: true,
        selection: false,
        stateful: true
    });
    
    canvas.isDrawingMode = true;
    canvas.freeDrawingBrush.color = "black";
    canvas.freeDrawingBrush.width = 2;
    
    canvas.on("path:created", function(options) {
        clip(options.path);
    });
    
    function clip(path) {
        canvas.isDrawingMode = false;
        canvas.remove(path);
    
        let mask = new fabric.Path(path.path, {
            top: object.top,
            left: object.left,
            objectCaching: false,
            strokeWidth: 0,
        		scaleX : 1/object.scaleX,
            	scaleY : 1/object.scaleY,
            pathOffset: {
                x: 0,
                y: 0
            }
        });
    
        let originalObjLeft = object.left,
            originalObjTop = object.top,
            originalMaskScaleX = mask.scaleX,
             originalMaskScaleY = mask.scaleY,
              originalObjScaleX = object.scaleX,
             originalObjScaleY = object.scaleY;
    
        object.set({
            clipTo: function(ctx) {
           		
                mask.set({
                    left: -object.width / 2   -( mask.width / 2  * originalMaskScaleX) - originalObjLeft/originalObjScaleX ,
                    top: -object.height / 2   -( mask.height / 2 * originalMaskScaleY) - originalObjTop/originalObjScaleY ,
                    objectCaching: false
                });
                mask.render(ctx);
            }
        });
    
        canvas.requestRenderAll();
    }
    
    // image
    
    let image = new Image();
     
    
    image.onload = function() {
        object = new fabric.Image(image, {
            width: 500,
            height: 500,
            scaleX: 0.8,
            scaleY: 0.8,
           // angle: 45,
            top: 50,
            left: 100
        });
    
        canvas.add(object);
    };
    
    image.src = "http://i.imgur.com/8rmMZI3.jpg";
    
    

    You can check here for loadFromJSON support. The only problem remains is when the object is rotated.

提交回复
热议问题