JS应用于每个画布(多个)

时间:2014-07-01 12:41:23

标签: javascript html5 canvas

我想在同一页面上的多个画布元素上使用StackBlur.js;但是使用Zurb提供的示例,我只能将它应用于第一个canvas元素;它忽略了其他人。

任何想法如何使这个代码更通用,以适用于每个canvas元素,而不仅仅是一个?

JS(由Zurb)是这样的:

  $(function() {
  // Change this value to adjust the amount of blur
  var BLUR_RADIUS = 100;

  var canvas = document.querySelector('[data-canvas]');
  var canvasContext = canvas.getContext('2d');

  var image = new Image();
  image.src = document.querySelector('[data-canvas-image]').src;

  var drawBlur = function() {
    var w = canvas.width;
    var h = canvas.height;
    canvasContext.drawImage(image, 0, 0, w, h);
    stackBlurCanvasRGBA('heroCanvas', 0, 0, w, h, BLUR_RADIUS);
  };

  image.onload = function() {
    drawBlur();
  }
});

相关的HTML是:

<canvas class="hero__background" id="heroCanvas" width="200" height="200" data-canvas></canvas>

<!-- Our image to be blurred -->
<img data-canvas-image style="display: none" src="path/to/image.jpg" />

谢谢!

1 个答案:

答案 0 :(得分:0)

将代码循环包含在具有该属性的所有元素(在本例中为data-canvas)中,如此

$('[data-canvas]').each(function(){
  var $el = $(this);
  // insert their code here and change it to reference the correct image each time
});

所以最后你可以单独引用页面上的每个画布,如下所示:

$(function(){

  // our iteration
  $('[data-canvas]').each(function(){
    var $el = $(this);

    var BLUR_RADIUS = 100;
    var canvas = this; // canvas is the element we're iterating over
    var canvasContext = canvas.getContext('2d');

    var image = new Image();

    // I changed the line below of theirs to refer to the canvases attributes
    // we're iterating over above
    image.src = $el.attr('data-src'); 

    var drawBlur = function() {
      var w = canvas.width;
      var h = canvas.height;
      canvasContext.drawImage(image, 0, 0, w, h);

      var id = $el.attr('id'); // use the id from the canvas
      stackBlurCanvasRGBA( id, 0, 0, w, h, BLUR_RADIUS); 
    };

    image.onload = function() {
      drawBlur();
    }

  });
});

所以现在我们不需要图像只有他们的src attributes, which now live on the canvases as data-src`。 html可以如下:

<canvas class="hero__background" id="heroCanvas1" data-src="/image/location.jpg" width="200" height="200" data-canvas></canvas>
<canvas class="hero__background" id="heroCanvas2" data-src="/image/location2.jpg" width="200" height="200" data-canvas></canvas>

更新:我意识到您在画布中显示信息,因此需要不止一个。上面更新的代码。

更新2 :我意识到堆栈模糊依赖于每个调用的id,所以你需要依次从每个画布获取它,更新上面的代码

除了:我建议按类而不是属性迭代画布,但我使用它就像你的html中那样。我建议为每个类添加一个类,并将迭代更改为类似的东西:

$('.blurImgCanvas').each(function(){....})