Reputation: 5863
I have a script like:
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) {
canvas.height = oImg.height
canvas.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 I am applying grayscale
filter to the image and I want to convert that image to url.
I am getting the url perfectly but the size of the image is not proper. I am getting only left top part of the image that also without of filter.
What might be wrong here. From the documentation I got this approach to apply filter.
Thank you
Upvotes: 0
Views: 578
Reputation: 10211
The only problems I can see are these two lines of code:
canvas.setHeight(oImg.height);
canvas.setWidth(oImg.width);
I changed your example to render the result in a image, take a look to the runnable snippet below:
canvas.height = oImg.height
canvas.width = oImg.width
that should be:
canvas.setHeight(oImg.height);
canvas.setWidth(oImg.width);
and also, since applyFilters
is asynchronous, I moved your toDataUrl in the callback.
(function filter(url) {
var c = document.createElement('canvas')
c.id = "canvas_greyscale"
var canvas = new fabric.Canvas(c.id)
fabric.Image.fromURL(url, function(oImg) {
oImg.width = 100;
oImg.height = 100;
canvas.setHeight(oImg.height);
canvas.setWidth(oImg.width);
oImg.filters.push(new fabric.Image.filters.Grayscale())
oImg.applyFilters(
function(){
canvas.add(oImg);
var img = canvas.toDataURL();
$('#myimg')[0].src = img;
}
);
}, {
crossOrigin: "Anonymous"
})
})('http://i.imgur.com/fHyEMsl.jpg');
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='myimg' />
Upvotes: 1