JS在画布上绘制图像

时间:2014-03-22 01:55:53

标签: javascript css html5 canvas

我试图将多个图像放在彼此堆叠的单独Canvas图层上,但图像不在画布上绘图。有人可以帮助我解决我所缺少的问题吗? 感谢

CSS

   .positionCanvas{
            position: absolute;
            left:0;
            right:0;
            margin-left:auto;
            margin-right:auto;
        background: rgba(255,255,255,0);
    }

    #logoCanvas{
        position: relative;
    }

HTML

<div id="logoCanvas">
        <canvas class="positionCanvas" width="300" height="300" id="outerRingCanvas">

        </canvas>
        <canvas class="positionCanvas" width="300" height="300" id="crossCanvas">

        </canvas>
        <canvas class="positionCanvas" width="300" height="300" id="innerRingsCanvas">

        </canvas>
        <canvas class="positionCanvas" width="300" height="300" id="centreCanvas">

        </canvas>

    </div>

JAVASCRIPT

var outerRing = document.getElementById('outerRingCanvas'),
    cross = document.getElementById('crossCanvas'),
    innerRings = document.getElementById('innerRingsCanvas'),
    centre = document.getElementById('centreCanvas');



var outerCtx = outerRing.getContext('2d'),
    crossCtx = cross.getContext('2d'),
    innerRingsCtx = innerRings.getContext('2d'),
    centreCtx = centre.getContext('2d');

var ctxArray = [outerCtx, crossCtx, innerRingsCtx, centreCtx];

var outerImg = new Image(),
    crossImg = new Image(),
    innerRingsImg = new Image(),
    centreImg = new Image();

var imgArray = [outerImg, crossImg, innerRingsImg, centreImg];

    outerImg.src = "logo_ring.png";
    crossImg.src = "logo_cross.png";
    innerRingsImg.src = "logo_centre_rings.png";
    centreImg.src = "logo_centre.png";
placeLogos(ctxArray);
crossCtx.drawImage(crossImg, 0, 0, 300, 300);



function placeLogos(array){
    for(var i = 0; i < array.length; i++){
        array[i].drawImage(imgArray[i], 100, 100, 100, 100);
        array[i].fillStyle = "rgba(233,100,10,0.2)"
        array[i].fillRect(0, 0, 300, 300);

    }
}

1 个答案:

答案 0 :(得分:1)

使用onload机制,因为图像加载是异步的。如果您不使用此图像,则在尝试使用图像时可能无法完全加载图像,而将画布留空。

...

var imageCount = 4;

outerImg.onload = loader;
crossImg.onload = loader;
innerRingsImg.onload = loader;
centreImg.onload = loader;

outerImg.src = "logo_ring.png";
crossImg.src = "logo_cross.png";
innerRingsImg.src = "logo_centre_rings.png";
centreImg.src = "logo_centre.png";

function loader() {
    imageCount--;

    if (imageCount === 0) {
        placeLogos(ctxArray);
        crossCtx.drawImage(crossImg, 0, 0, 300, 300);
    }
}