keeping current image in canvas on redraw


#1

I want to apply a filter to a canvas. I am bringing the image in using ajax.

fetch('/catpicture')
.then(response => response.blob())
.then(blob => createImageBitmap(blob))
.then((bitmap) => {
    ctx.drawImage(bitmap, 0, 0, 200, 200,);
})

As I understand it, I can’t just use ctx.filter = 'blur(10px)' afterwards. I need to redraw the canvas for the filter to show. How do I keep the image that is in the canvas?


#2

Do you want to filter the whole canvas or just the image? If you want to filter just the image then set the filter before you call drawImage. Setting the filter sets the state of how the canvas draws new things, so setting it before drawImage means when drawImage is called, it will get filtered.

If you want to filter everything, and you haven’t set filter up to this point, then you’ll want to draw your image first, then copy your canvas entirely, set the filter, and redraw the canvas over again from the copy.


#3

I only want to apply the filter to an image, but I want an input to allow a visitor to alter the filter, so it needs to update. When you say “copy your canvas entirely”, how do I do that?


#4

Use getImageData and putImageData


#5

I tried
ctx.filter = ‘blur(15px)’;
var imagedata = ctx.getImageData(0,0, 300,300);
ctx.putImageData(imagedata, 0, 0);

but it didn’t work. Where did I go wrong?


#6

You’re missing the whole drawImage part - all the code you posted earlier