fabricjs set clipped object as background to canvas after clipping

耗尽温柔 提交于 2019-12-06 08:07:38

Actually you cropped the rendering of the canvas.

To save the cropped area you must use Canvas.toDataURL() method, as you can see there is parameters top, left, width, height just use the same as you put into ctx.rect(left, top, width, height) and it will returns you a string representing the cropped area (base64 encoded).

Then use this string as your canvas new background image with Canvas.setBackgrounsImage

Your code should look like:

function crop(url, name, left, top, width, height, callback) {
    var c = document.createElement('canvas')
    var id = "canvas_" + name
    c.id = id
    var canvas = new fabric.Canvas(id)

    fabric.Image.fromURL(url, function(oImg) {

        oImg.set({
            selectable:false,
        })
        canvas.setDimensions({width:oImg.width, height:oImg.height})
        canvas.add(oImg)
        canvas.centerObject(oImg)
        canvas.renderAll()
        var img = canvas.toDataURL({
                      format: 'image/png',
                      left: left,
                      right: right,
                      width: width,
                      height: height
                  })
        console.log(img)
        canvas.setBackgroundImage(img)
        callback(img)
    }, {crossOrigin: "Anonymous"})
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!