2

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/

Casey Falk
  • 2,617
  • 1
  • 18
  • 29
  • 2
    The point of an `ID` is for it to be unique to *one* element. You might want to look into that more. So I'd recommend you look into learning HTML. Apart from that, you need to get the context for every canvas, and draw on every canvas too. – Some Guy Jul 16 '14 at 18:29
  • You have to treat every canvas seperately, with a unique id, otherwise use a class and perform actions incrementally to them. – Sam Jul 16 '14 at 18:31

1 Answers1

0

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';
});
Community
  • 1
  • 1
Casey Falk
  • 2,617
  • 1
  • 18
  • 29