Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript fabricjs filter do not return filtered canvas to url

export function filter(url) {
    var c = document.createElement('canvas')
    c.id = "canvas_greyscale"
    var canvas = new fabric.Canvas('canvas_greyscale')
    fabric.Image.fromURL(url, function(oImg) {
        c.height = oImg.height
        c.width = oImg.width
        oImg.filters.push(new fabric.Image.filters.Grayscale())
        oImg.applyFilters(canvas.renderAll.bind(canvas))
        canvas.add(oImg)
        var img = canvas.toDataURL('image/png')
        console.log(img)
        return img
    }, {crossOrigin: "Anonymous"})
}

Here my canvas is rendered with grayscale filter. It does not have issue but when I try to convert canvas to url it is giving me the canvas without filter.

I dont know whats wrong in here..

What am I doing wrong. I want to convert the canvas that have filter to url

var img = canvas.toDataURL('image/png') gives me image without filter

Need help

like image 238
varad Avatar asked Oct 29 '22 20:10

varad


1 Answers

applyFilters is asynchronous (that's why you pass a renderAll callback in it).
You need to call toDataURL in its callback otherwise you're exporting the canvas before the filter is applied.

Here is a rough adaptation of your code :

function filter(url, callback) {
  var c = document.createElement('canvas');
  c.id = "canvas_greyscale";
  var canvas = new fabric.Canvas('canvas_greyscale');
  // the applyFilters' callback
  var onend = function() {
    canvas.renderAll();
    var img = canvas.toDataURL('image/png');
    callback(img);
  }

  fabric.Image.fromURL(url, function(oImg) {
    canvas.setDimensions({width:oImg.width, height:oImg.height});

    oImg.filters.push(new fabric.Image.filters.Grayscale())
    // here we pass the export function
    oImg.applyFilters(onend)
    
    canvas.add(oImg)
  }, {
    crossOrigin: "Anonymous"
  })
}

var url = 'https://upload.wikimedia.org/wikipedia/commons/5/5b/Supernumerary_rainbow_03_contrast.jpg'
filter(url, function(dataURI) {
  output.src = dataURI;
  original.src = url
})
img{ width: 50%}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.js"></script>
<img id="output"><br>
original Image: © Andrew Dunn CC-By-SA 2.0 <br>
<img id="original">
like image 120
Kaiido Avatar answered Nov 09 '22 12:11

Kaiido