2014-01-22 88 views
0

我想在主幹中添加模糊的背景圖像。我有一個HandlebarsJS-HTML模板BackboneJS - 模糊的背景圖像

<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 -element,只是呈現<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> 

有誰知道這個問題可能是什麼?

回答

0

我試過你的代碼,並得到了在控制檯錯誤象下面這樣:

Uncaught ReferenceError: stackBoxBlurCanvasRGB is not defined 

當我評論stackBoxBlurCanvasRGB函數調用我在畫布渲染圖像。

這裏是演示http://jsfiddle.net/bMxe8/和這個http://jsfiddle.net/bMxe8/1/與註釋stackBoxBlurCanvasRGB函數。

所以你需要獲得工作函數stackBoxBlurCanvasRGB才能使它工作。