yasuperu
yasuperu

Reputation: 77

Show multiple images specific X, Y, width and height in JavaScript canvas

I'm currently trying to make a canvas that shows a specific crop of an image. I have created a little piece of code that can do this with a single image, but I wonder if it is possible and how to use a json file that has multiple cropped images to show in a single canvas?

the code:

<canvas id="canvas"></canvas>
    
<script type="text/javascript">
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var img = new Image();
    img.onload = function () {

        clipImage(img, 140, 2, 120, 110);

    }
    img.crossOrigin = "anonymous";
    img.src = "image.jpg";

    function clipImage(image, clipX, clipY, clipWidth, clipHeight) {

        // draw the image to the canvas
        // clip from the [clipX,clipY] position of the source image
        // the clipped portion will be clipWidth x clipHeight
        ctx.drawImage(image, clipX, clipY, clipWidth, clipHeight,
        0, 0, clipWidth, clipHeight);
    }
</script>

example of the JSON:

[{"name":"image.jpg","clipWidth":512,"clipHeight":512, "clipX":0,"clipY":0},
{"name":"image2.jpg","clipWidth":512,"clipHeight":512, "clipX":30,"clipY":60}]

Upvotes: 0

Views: 120

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17594

Looks like you got most of the way there...
Now it is just a loop over that json data, not sure how are you getting the data so as a quick example I'm using a textarea, see code below

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var field = document.getElementById("data");
var data = JSON.parse(field.value);

for (let i = 0; i < data.length; i++) {
  var img = new Image();
  img.onload = function() {
    clipImage(img, data[i].clipX, data[i].clipY, data[i].clipWidth, data[i].clipHeight);
  }
  img.src = data[i].name;
}

function clipImage(image, clipX, clipY, clipWidth, clipHeight) {
  ctx.drawImage(image, clipX, clipY, clipWidth, clipHeight);
}
<canvas id="canvas"></canvas>
<br>
<textarea id="data" rows="9" cols="64">
[
{"name":"https://i.sstatic.net/UFBxY.png","clipWidth":70,"clipHeight":80, "clipX":0,"clipY":0},
{"name":"https://i.sstatic.net/UFBxY.png","clipWidth":89,"clipHeight":99, "clipX":70,"clipY":10},
{"name":"https://i.sstatic.net/UFBxY.png","clipWidth":50,"clipHeight":60, "clipX":170,"clipY":30}
]
</textarea>

Too keep the code short I removed all your comments and simplified your ctx.drawImage you should not have any problems changing all that to suit your needs

Upvotes: 1

Related Questions