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
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With