Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas blur function - no third party plug-ins

I have been searching on the internet for a simple way to blur a canvas image. I thought it would be easy to find information about how to program the gaussian blur function but every time I found something, it always included a lot of unneeded functions like animation and so on. All I want is to take an image -> draw it in canvas -> blur image-> output image to data -> apply the data to a div element -> then delete the canvas element.

I saw this one about motion blur: Better canvas motion blur Which didn't require that much code. How do I do something similar but in gaussian blur instead of motion blur?

like image 426
Corfitz. Avatar asked Jun 05 '13 07:06

Corfitz.


2 Answers

In the example you posted, the HTML5 globalAlpha property of the target image is changed to change its opacity, and then the image is painted 10 times on a different vertical point to create the illusion of a motion blur.

For a normal Gaussian blur, you can use the regular CSS3 filter / feGaussianBlur attributes. Check here for an example:

http://css-plus.com/2012/03/gaussian-blur/

In particular, the section named "SVG blur filter applied to a SVG image element"

There are more techniques to do this, including Javascript plugins like the following:

  • http://blurjs.com/
  • http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html

However, the CSS3 filter / feGaussianBlur attributes should be the simplest to use, for your needs.

like image 130
Filippos Karapetis Avatar answered Oct 15 '22 10:10

Filippos Karapetis


Try this:

blur = function (canvasId) {

    var c = document.getElementById(canvasId);
    var ctx = c.getContext("2d");
    ctx.globalAlpha = 0.3;

    var offset = 3;

    for (var i=1; i<=8; i+=1) {
        ctx.drawImage(c, offset, 0, c.width - offset, c.height, 0, 0, c.width-offset, c.height);
        ctx.drawImage(c, 0, offset, c.width, c.height - offset, 0, 0,c.width, c.height-offset);
    }
};

blur("myCanvas");

like image 21
Cibo FATA8 Avatar answered Oct 15 '22 11:10

Cibo FATA8