BackboneJS - 模糊的背景图像

时间:2014-01-22 13:30:02

标签: javascript jquery backbone.js

我正在尝试在Backbone中添加模糊的背景图像。我有一个HandlebarsJS-HTML模板

<div class="bg" data-src="./demopics/hlowq.jpg" id="bgc"></div>

我希望将其渲染为元素<div id="bgWrap"></div>中的视图。我正在使用我在网上找到的blurscript,看起来像这样。

//create image object
 var imageObj = new Image();

//when image is finished loading
  imageObj.onload = function() {
        //get size
        var w = imageObj.naturalWidth;
        var h = imageObj.naturalHeight;

        var canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
        //create virtual canvas
        var ctx = canvas.getContext('2d');

        //draw the image on it
        ctx.drawImage(imageObj, 0, 0);

        //apply the blur
        stackBoxBlurCanvasRGB(ctx, 0, 0, w, h, 11, 2);

        //add grey filter
        ctx.fillStyle='rgba(64,64,64,0.4)';
        ctx.fillRect(0,0,w,h);

        //and display it in 1 second using a fade
        var $canvas = $(canvas) 

        $("#bgc").append(canvas);
        $canvas.show();
        var canvasRatio = $canvas.width()/$canvas.height();
        var windowRatio = $(window).width()/$(window).height();
        if (canvasRatio > windowRatio){
            $canvas.css({
                "height": "100%",
                "width" : "auto"
            });
        } else {
            $canvas.css({
                "width": "100%",
                "height": "auto"
            });
        }
        $canvas.css({
            "marginLeft" : -$canvas.width()/2+"px",
            "marginTop" : -$canvas.height()/2+"px"
        });
        window.onresize = function(){
            var canvasRatio = $canvas.width()/$canvas.height();
            var windowRatio = $(window).width()/$(window).height();
            if (canvasRatio > windowRatio){
                $canvas.css({
                    "height": "100%",
                    "width" : "auto"
                });
            } else {
                $canvas.css({
                    "width": "100%",
                    "height": "auto"
                });
            }
            $canvas.css({
                "marginLeft" : -$canvas.width()/2+"px",
                "marginTop" : -$canvas.height()/2+"px"
             });
        }

 };

//set the source of the image from the data source
imageObj.src = $('#bgc').data("src");

由于某些原因我不知道,这不起作用。它不会创建canvas - 元素,只需在<div id="bGWrap">中呈现视图。

所以DOM看起来像:

<div id="bgWrap">
  <div class="bg" data-src="./demopics/hlowq.jpg" id="bgc"></div>
</div>

但它应该是:

<div id="bgWrap">
  <div class="bg" data-src="./demopics/hlowq.jpg" id="bgc"></div>
  <canvas some styles..... />
</div>

有谁知道这个问题可能是什么?

1 个答案:

答案 0 :(得分:0)

我已尝试过您的代码并在控制台中出现错误,如下所示:

Uncaught ReferenceError: stackBoxBlurCanvasRGB is not defined

当我评论stackBoxBlurCanvasRGB函数调用时,我得到了在画布中呈现的图像。

以下是演示http://jsfiddle.net/bMxe8/以及此http://jsfiddle.net/bMxe8/1/个评论stackBoxBlurCanvasRGB功能。

因此,您需要使用函数stackBoxBlurCanvasRGB才能使其正常工作。