gpt4 book ai didi

javascript - JS 在 Canvas 上绘制图像

转载 作者:太空宇宙 更新时间:2023-11-04 13:45:08 25 4
gpt4 key购买 nike

我正在尝试将多个图像粘贴到相互堆叠的单独 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);

}
}

最佳答案

使用 onload 机制,因为图像加载是异步的。如果您不使用它,当您尝试使用它们时图像可能不会完全加载,而 Canvas 为空白。

...

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);
}
}

关于javascript - JS 在 Canvas 上绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22572470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com