keeping current image in canvas on redraw

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

.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?

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.

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?

Use getImageData and putImageData

1 Like

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?

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