我已創建2畫布,加載兩個不同的圖像,我想合併兩個畫布,然後顯示它作爲圖像在<div id="test"></div>
標記。畫布不合並,導致只顯示背景圖像
這裏是我的代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas to image</title>
</head>
<body>
<div>
<canvas id="card_canvas" width="800" height="500"></canvas>
<canvas id="card_canvas2" width="800" height="500"></canvas>
</div>
<div id="test"></div>
<button onclick="canvasToImage()">canvas to image</button>
<script>
var img1 = new Image();
img1.src = "images/img1.jpg";
var cuimg;
function canvasToImage(){
var canvass1 = document.getElementById("card_canvas");
var canvass2 = document.getElementById("card_canvas2");
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.drawImage(img1, 0, 0);
cuimg = new Image();
cuimg.onload = function(){
ctx2.drawImage(cuimg, 7, 92);
}
cuimg.src = "images/img2.jpg";
ctx1.drawImage(canvass2, 0, 0);
var imgdata = canvass1.toDataURL('image/png');
var mergeimg = document.createElement("img");
mergeimg.src = imgdata;
document.getElementById("test").appendChild(mergeimg);
}
</script>
</body>
</html>
這裏是img1.jpg:
這裏是img2.jpg:
此代碼結束僅顯示背景圖像:
我期待:
要調用ctx1.drawImage(canvas2)和canvas1.toDataURL(),而你還沒有畫上canvas2圖像:你把它畫到畫布上,這使得這個之前正確使用圖像的onload事件操作異步。此操作發生後,您需要調用邏輯跟蹤。 – Kaiido