使用javascript在图片中填充图片而不会出现重叠图像

时间:2014-06-07 19:43:19

标签: javascript css html5 canvas

要使用以下代码填充带有多个图像的画布:

<canvas id="myCanvas"></canvas>
<script>
    function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        // get num of sources
        for ( var src in sources) {
            numImages++;
        }
        for ( var src in sources) {
            images[src] = new Image();
            images[src].onload = function() {
                if (++loadedImages >= numImages) {
                    callback(images);
                    }
            };
            images[src].src = sources[src];
        }
    }
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    fitToContainer(canvas);
    var sources = {
        darthVader : 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
        yoda : 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'
    };

    loadImages(sources, function(images) {
        context.drawImage(images.darthVader, 0,0);
        context.drawImage(images.yoda, 0, 0);
    });

    function fitToContainer(canvas) {
        canvas.style.width = '100%';
        canvas.style.height = '100%';
        canvas.width = canvas.offsetWidth;
        canvas.height = canvas.offsetHeight;
    }
    </script>

虽然这实际上是用图像填充画布,但我无法定位图像以便不重叠它们。我提前不知道照片的大小。是否有任何图书馆或框架可以轻松地为我做这个或我可以去哪个方向?

画布的大小有限,因为它位于父html元素中。

1 个答案:

答案 0 :(得分:1)

只需跟踪图像的累积宽度。

然后在该累积宽度的右侧绘制下一个图像

loadImages(sources, function(images) {
    var nextX=0;
    context.drawImage(images.darthVader, nextX,0);
    nextX+=images.darthVader.width;
    context.drawImage(images.yoda, nextX, 0);
    nextX+=images.yoda.width;
    // ...and so on...
});