Reputation: 1884
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?
Upvotes: 6
Views: 12319
Reputation: 101
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");
Upvotes: 1
Reputation: 4652
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:
However, the CSS3 filter / feGaussianBlur attributes should be the simplest to use, for your needs.
Upvotes: 3