开发者

html canvas shape blur filter

There must be a way to do this. I have drawn a shape with the html5 canvas and I would like to blur it. As far as I know there is no native method so I assume a js library is needed. The problem is most libraries only blur images like this one fo开发者_高级运维r example. Is this possible?


myContext.filter = 'blur(10px)';

The CanvasRenderingContext2D.filter property of the Canvas 2D API provides filter effects like blurring or gray-scaling. It is similar to the CSS filter property and accepts the same functions. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter

it's still experimental but is supported by chrome & firefox atm.


You can use CSS to blur the canvas. If it's just the shape you want to blur then the shape will need to be on its own separate layer (canvas), which you could create on the fly.

Example:

canvas.style.webkitFilter = "blur(3px)";

You can un-blur the canvas again with:

canvas.style.webkitFilter = "blur(0px)";

This is probably the fastest (and simplest) way to blur a canvas – especially for mobile devices.


For a fast blur that is almost Gaussian I'd recommend StackBlur: http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html

Alternatively you could use this Superfast Box Blur with 2 iterations: http://www.quasimondo.com/BoxBlurForCanvas/FastBlurDemo.html


The pixastic library example you've linked to should actually work with a canvas element as the first argument rather than an image.

By default the pixastic library will try to replace the node you pass in with the canvas element that it creates. To prevent it from doing so you can include an option to specify to leave the DOM node and include a callback to handle the returned data yourself. Something like this:

Pixastic.process(canvas, "blur", { leaveDOM: true }, function(img) {
    canvas.getContext('2d').drawImage(img, 0, 0);
});

Alternatively, if you don't want to depend on a library, you can implement a blur yourself using getImageData(), manipulating the returned pixel data and using putImageData() to draw the blurred image back to the canvas.

One other thing to note is that individual pixel manipulation is slow and may not work well for large images. If that's a problem, you might try scaling the image down and scaling back up for a quickly done blur like effect. Something like this:

ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2);
ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2, 0, 0, canvas.width, canvas.height);


https://github.com/nodeca/glur - it implements gaussian blur via IIR filter. See demos.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜