2013-02-18 7 views
-2

Я пытаюсь использовать эту функцию для большого количества изображений, но сейчас я не могу, потому что она получает элемент по идентификатору, как я могу изменить функцию, чтобы заставить ее получить класс элемента?Получить элемент по классу в функции ID

/* Canvas multiply effect */ 
    var multiplyFilter = (function() { 
     //** private vars **// 
     var multiplyColor, 
       imageBottom, imageId, 
       canvas; 

     //** private functions **// 
     function createCanvas() { 
      canvas = document.createElement('canvas'); 
      canvas.width = imageBottom.width; 
      canvas.height = imageBottom.height; 
      imageBottom.parentNode.insertBefore(canvas, imageBottom); 
      // no canvas support? 
      if (!canvas.getContext) { return; } 

      draw(); 
     } 
     function draw() { 
      var context, imgData, pix, 
        w = imageBottom.width, 
        h = imageBottom.height; 
      // get 2d context 
      context = canvas.getContext('2d'); 
      // draw the image on the canvas 
      context.drawImage(imageBottom, 0, 0); 
      // Get the CanvasPixelArray from the given coordinates and dimensions. 
      imgData = context.getImageData(0, 0, w, h); 
      pix = imgData.data; 
      // Loop over each pixel and change the color. 
      for (var i = 0, n = pix.length; i < n; i += 4) { 
       pix[i ] = multiplyPixels(multiplyColor[0], pix[i ]); // red 
       pix[i+1] = multiplyPixels(multiplyColor[1], pix[i+1]); // green 
       pix[i+2] = multiplyPixels(multiplyColor[2], pix[i+2]); // blue 
       // pix[i+3] is alpha channel (ignored) 

       // another check to see if image is still empty 
       if(i < 5 && !pix[i] && !pix[i+1] && !pix[i+2] && !pix[i+3]) { 
        canvas.parentNode.removeChild(canvas); 
        setTimeout(function() { multiplyFilter.init(imageId, multiplyColor); }, 500); 
        return false; 
       } 
      } 
      // Draw the result on the canvas 
      context.putImageData(imgData, 0, 0); 
     } 

     //** helper function **// 
     function multiplyPixels(topValue, bottomValue) { 
      // the multiply formula 
      return topValue * bottomValue/255; 
     } 

     //** public functions **// 
     return { 
      init : function(imgId, color) { 
       imageId = imgId; 
       imageBottom = document.getElementById(imageId); 
       multiplyColor = color; 

       // lauch the draw function as soon as the image is loaded 
       if(imageBottom && imageBottom.clientWidth > 50) { // image loaded 
        createCanvas(); 
       } else { // not yet ready 
        setTimeout(function() { multiplyFilter.init(imageId, color); }, 1000); 
       } 
      } 
     } 
    })(); 

    multiplyFilter.init('multiply_hover', [255, 105, 0]); 
+0

Какие браузеры вы планируете поддерживать? – leopic

+0

IE 8 и выше, хром и firefox – codek

ответ

2

Изменение document.getElementById(imageId) в document.querySelectorAll(...) и вы можете поддерживать несколько элементов с помощью синтаксиса селектора CSS. Вам просто нужно перебирать возвращаемые элементы, где перед тем, как вы ожидали одного элемента.

... Что-то примерно так (не тестировалось):

/* Canvas multiply effect */ 
var multiplyFilter = (function() { 
    //** private vars **// 
    var multiplyColor, 
      images, imageSelector, 
      canvases = []; 

    //** private functions **// 
    function createCanvases() { 
     var canvas, image; 

     for (var i=0; i<images.length; i++) { 
      canvas = document.createElement('canvas'); 

      // no canvas support? 
      if (i === 0 && !canvas.getContext) { return; } 

      image = images[i]; 

      canvas.width = image.width; 
      canvas.height = image.height; 
      image.parentNode.insertBefore(canvas, image); 
      draw(image, canvas); 
     } 
    } 
    function draw(image, canvas) { 
     var context, imgData, pix, 
       w = image.width, 
       h = image.height; 
     // get 2d context 
     context = canvas.getContext('2d'); 
     // draw the image on the canvas 
     context.drawImage(image, 0, 0); 
     // Get the CanvasPixelArray from the given coordinates and dimensions. 
     imgData = context.getImageData(0, 0, w, h); 
     pix = imgData.data; 
     // Loop over each pixel and change the color. 
     for (var i = 0, n = pix.length; i < n; i += 4) { 
      pix[i ] = multiplyPixels(multiplyColor[0], pix[i ]); // red 
      pix[i+1] = multiplyPixels(multiplyColor[1], pix[i+1]); // green 
      pix[i+2] = multiplyPixels(multiplyColor[2], pix[i+2]); // blue 
      // pix[i+3] is alpha channel (ignored) 

      // another check to see if image is still empty 
      if(i < 5 && !pix[i] && !pix[i+1] && !pix[i+2] && !pix[i+3]) { 
       canvas.parentNode.removeChild(canvas); 
       setTimeout(function() { multiplyFilter.init(imageId, multiplyColor); }, 500); 
       return false; 
      } 
     } 
     // Draw the result on the canvas 
     context.putImageData(imgData, 0, 0); 
    } 

    //** helper function **// 
    function multiplyPixels(topValue, bottomValue) { 
     // the multiply formula 
     return topValue * bottomValue/255; 
    } 

    //** public functions **// 
    return { 
     init : function(selector, color) { 
      imageSelector = selector; 
      images = document.querySelectorAll(imageSelector); 
      multiplyColor = color; 

      // lauch the draw function as soon as the image is loaded 
      if(images.length) { 
       var imagesLoaded = true; 
       for (var i=0; i<images.length; i++) { 
        if (images[i].clientWidth < 50) { 
         imagesLoaded = false; 
         break; 
        } 
       } 

       if (imagesLoaded) { 
        createCanvases(); 
        return; 
       } 
      } 

      // not yet ready 
      setTimeout(function() { 
       multiplyFilter.init(imageSelector, color); 
      }, 1000); 
     } 
    } 
})(); 

// selects all images with class 'multiply_hover' 
multiplyFilter.init('.multiply_hover', [255, 105, 0]); 
+0

Я положил его и использовал класс на изображении, но он не работает на последнем хроме – codek

+0

«Не работает» просто не является достаточным описанием проблемы. Попробуйте код в моем ответе. –

+0

Итак, я положил код в свой ответ, и теперь я получаю эту ошибку: «imageBottom не определен» – codek

Смежные вопросы