Search code examples
javascripthtmlcanvascrop

Using Several Canvases at Once


I want to crop several images in a page using HTML5's canvas tag and JavaScript. The problem is that the page shows just one of the images.

What should I do? The code I tried is below:

<canvas id="myCanvas" width="300" height="300"></canvas>
<canvas id="myCanvas" width="300" height="300"></canvas>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var imageObj = new Image();

  imageObj.onload = function() {
    // draw cropped image
    var sourceX = 0;
    var sourceY = 0;
    var sourceWidth = 200;
    var sourceHeight = 150;
    var destWidth = sourceWidth;
    var destHeight = sourceHeight;
    var destX = canvas.width / 2 - destWidth / 2;
    var destY = canvas.height / 2 - destHeight / 2;

    context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
  };

imageObj.src ='http://static.adzerk.net/Advertisers/3478c54721cd466fb6f7d3afe16e97d4.gif';

</script>

The Fiddle: http://jsfiddle.net/soheilyou/54VTh/


Solution

  • Just as Some Guy said, you are using the same id for each canvas -- that's a no-no. Try giving each one a unique id or using a class instead.

    Then, it's just a matter of grabbing the elements one by one -- which you could do with JavaScript or perhaps more easily with jQuery (below).

    Check out this updated Fiddle or see this JavaScript snippet:

    var canvases = $('.myCanvas');
    $(canvases).each(function () {
        var canvas = $(this).get(0); //Grab the canvas node from the jQuery container.
        var context = canvas.getContext('2d');
        var imageObj = new Image();
    
        imageObj.onload = function () {
            var sourceX = 0;
            var sourceY = 0;
            var sourceWidth = 200;
            var sourceHeight = 150;
            var destWidth = sourceWidth;
            var destHeight = sourceHeight;
            var destX = canvas.width / 2 - destWidth / 2;
            var destY = canvas.height / 2 - destHeight / 2;
    
            context.drawImage(imageObj, sourceX, sourceY, 
                              sourceWidth, sourceHeight, destX, 
                              destY, destWidth, destHeight);
        };
    
        imageObj.src = 'path/to/your/image.png';
    });