简体   繁体   English

如何在画布上获取背景图像和绘图路径中的图像?

[英]how to get the image in drawing path with background image in fabric canvas?

I want lasso crop in fabric canvas. 我想在织物帆布中套索。 For now I can draw path on canvas. 现在,我可以在画布上绘制路径。 but I don't know how to cut out path with background image. 但是我不知道如何用背景图像切出路径。 Is there any way I can save the cut image? 有什么方法可以保存剪切的图像? Here is my code 这是我的代码

    const canvas = document.getElementById('c');
    const ctx = canvas.getContext('2d');
    const img = document.createElement('IMG');

    const base64data = canvas.toDataURL("image/jpeg")


    img.onload = function() {
        const OwnCanv = new fabric.Canvas('c', {
            isDrawingMode: true
        });


        canvas.width = img.width;
        canvas.height = img.height;

        const imgInstance = new fabric.Image(img, {
            async: false,
            left: 0,
            top: 0,
            lockMovementX: true,
            lockMovementY: true
        });
        OwnCanv.add(imgInstance);


        OwnCanv.freeDrawingBrush.color = "purple"
        OwnCanv.freeDrawingBrush.width = 5

        OwnCanv.on('path:created', function(option) {
            const path = option.path;
            OwnCanv.isDrawingMode = false;
            OwnCanv.remove(imgInstance);
            OwnCanv.remove(path);
            OwnCanv.clipTo = function(ctx) {
                path.render(ctx);
            };
            OwnCanv.add(imgInstance);
        });
    }

img.src = base64data

}

You can do it like this: 您可以这样做:

OwnCanv.on('path:created', function(option) {
  var path = option.path;
  imgInstance.clipTo = function(ctx) {
      //save context state
      ctx.save();
      //reset context tranformation matrix
      ctx.setTransform(1,0,0,1,0,0);
      //render the path
      path.render(ctx);
      //restore context state
      ctx.restore();
  };
  OwnCanv.renderAll();      
});

See here: https://jsfiddle.net/f82omjsr/ 看到这里: https : //jsfiddle.net/f82omjsr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM