简体   繁体   English

在 JavaScript canvas 中显示多个图像特定的 X、Y、宽度和高度

[英]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.我目前正在尝试制作一个 canvas 来显示图像的特定裁剪。 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?我已经创建了一小段代码,可以使用单个图像执行此操作,但我想知道这是否可能以及如何使用具有多个裁剪图像的 json 文件以显示在单个 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: JSON 的示例:

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

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现在它只是 json 数据的循环,不确定你是如何获取数据的,所以作为一个快速示例,我使用的是 textarea,请参见下面的代码

 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":"http://i.stack.imgur.com/UFBxY.png","clipWidth":70,"clipHeight":80, "clipX":0,"clipY":0}, {"name":"http://i.stack.imgur.com/UFBxY.png","clipWidth":89,"clipHeight":99, "clipX":70,"clipY":10}, {"name":"http://i.stack.imgur.com/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保持代码简短我删除了你所有的评论并简化了你的ctx.drawImage你应该没有任何问题改变所有这些以满足你的需要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM