Daimz
Daimz

Reputation: 3281

add HTML5 Canvas b&w effect to more than one image

I am wanting to create a gallery using HTML5 Canvas Black for hover effects however I am having a bit of trouble.

I can get the effect work perfectly on one element but I can't seem to get it to work on more than one.

Here is what I have:

(function() {  
      var supportsCanvas = !!document.createElement('canvas').getContext;  
      supportsCanvas && (window.onload = greyImages);  

      function greyImages() {  
          var ctx = document.getElementsByTagName("canvas")[0].getContext('2d'),  
              img = document.getElementById("cvs-src"),  
              imageData, px, length, i = 0,  
              grey;  

          ctx.drawImage(img, 0, 0);  

          // Set 500,500 to the width and height of your image.  
          imageData = ctx.getImageData(0, 0, 378, 225);  
          px = imageData.data;  
          length = px.length;  

          for ( ; i < length; i+= 4 ) {  
              grey = px[i] * .1 + px[i+1] * .1 + px[i+2] * .1;  
              px[i] = px[i+1] = px[i+2] = grey;     
           }

          ctx.putImageData(imageData, 0, 0);  
      }  
  })();

HTML:

<article id="respond" class="first">
    <a href="gitano.php" rel="#overlay" style="text-decoration:none">
        <img id="cvs-src" src="images/thumbnails/regular/gitano.png" />  
        <canvas width=378 height=225></canvas> 
        <div class="caption">
            <p><img class="enlarge" src="images/enlarge.png"/>Click To <em>View Project</em></p>
        </div>
    </a>    
</article>

CSS:

   figure article img {
width: 100%;
padding: 0;
margin: 0;
border: 0;
vertical-align:bottom;
   }

   figure article:hover img {
display: block;
   }

   figure article canvas {
width: 100%;
padding: 0;
margin: 0;
border: 0;
position: absolute;  
left: 0;  
top: 0;  
opacity: 1;  
-webkit-transition: all 1s;  
-moz-transition: all 1s;  
-o-transition: all 1s;  
-ms-transition: all 1s;  
transition: all 1s;
    }  

    figure article canvas:hover {  
        opacity: 0;  
    }  

Upvotes: 0

Views: 515

Answers (1)

James Clark
James Clark

Reputation: 1821

It looks like you are applying it to only one canvas here:

var ctx = document.getElementsByTagName("canvas")[0].getContext('2d')

You are fetching the first canvas ([0]) and getting its context. Perhaps this would be better:

var canvases = document.getElementsByTagName("canvas");
for (var j = 0; j < canvases.length; j ++) {
  var ctx = canvases[j].getContext('2d'),  
      img = document.getElementById("cvs-src"),  
      imageData, px, length, i = 0,  
      grey;  
  // and so on...
}

Upvotes: 1

Related Questions