[英]Javascript + jQuery, applying a blur effect to background images
Is there a way to apply a "blur" effect on a background image in Javascript/jQuery? 有没有办法在Javascript / jQuery中对背景图像应用“模糊”效果?
[edit] By "blur" I mean a Gaussian/Motion blur not a drop shadow :) [编辑]“模糊”是指高斯/运动模糊而不是阴影:)
Thank you. 谢谢。
The simplest, most cross-browser-friendly way to do this will be to create blurred and non-blurred versions of your background image ahead of time, and use JavaScript to swap the blurred version in when you want to. 最简单,最易于跨浏览器访问的方法是提前创建背景图像的模糊和非模糊版本,并在需要时使用JavaScript交换模糊版本。 Something like:
就像是:
$('#hoverMe').hover(function ()
{
$(this).css('background-image', 'url(blurredBackground.png)');
});
Edit: It's a bit of a cop-out, but all you need to do is create a new image element for Pixastic to operate on. 编辑:这有点麻烦,但是您要做的就是为Pixastic创建一个新的图像元素以进行操作。 Since Pixastic uses a canvas anyway, you can let the library do the work for you, and then just call
toDataURL()
to get a URL string. 由于Pixastic仍然使用画布,因此您可以让该库为您完成工作,然后只需调用
toDataURL()
即可获取URL字符串。 Then, pass that string back into the background-image
CSS. 然后,将该字符串传递回
background-image
CSS。
Very basic demo here . 非常基本的演示在这里 。 Tested in Chrome, Firefox.
在Chrome,Firefox中进行了测试。
Notes: 笔记:
canvas
, as per the spec . canvas
的安全功能。 This is why my example image is jsbin's favicon, and not an image that's bigger/more interesting/from anywhere else. toDataURL()
so the browser doesn't have to repeat its work. toDataURL()
的结果,这样浏览器就不必重复其工作了。 I don't know how toDataURL()
works under the hood so this might not be entirely straightforward. toDataURL()
如何在toDataURL()
运行,因此这可能并不完全简单。 Happy blurring! 快乐模糊!
I encountered the same problem today, My solution was the following. 今天我遇到了同样的问题,下面是我的解决方案。 I used the regular way to use pixastic and blur an image.
我使用常规方法来使用像素模糊和模糊图像。 Pixastic then in my case created a canvas element.
然后在我的情况下,Pixastic创建了canvas元素。 I made sure this canvas element had an id, and by getting its data, i used the data to set my background-image.
我确保此canvas元素具有一个id,并通过获取其数据来使用该数据设置背景图像。
Example: 例:
HTML: HTML:
<div id="hiddenDiv" style="width:0px; height: 0px;"></div>
Javascript: Javascript:
var img = new Image();
img.id = "blurredImage"
img.onload = function() {
Pixastic.process(img, "blur", function(){
var canvas = document.getElementById('blurredImage');
var dataURL = canvas.toDataURL("image/png");
document.getElementById('blurredImage').style.backgroundImage = 'url("' + dataURL + '")';
});
}
document.getElementById("hiddenDiv").appendChild(img);
img.src = "myimage.jpg";
It's quite a workaround, however I had to use floating divs, which made me unable to use position absolute, and z-index's and I won't blurr tons of images. 这是一个非常好的解决方法,但是我不得不使用浮动div,这使我无法使用绝对位置,并且无法使用z-index,也不会模糊大量图像。
Goodluck! 祝好运!
有这个jquery-plugin blur.js可以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.