[英]Is there a way of drawing an image OVER HTML5 canvas 2d drawings?
每次我用谷歌搜索時,它都會給我反向解決方案的答案-在圖像上繪制內容。 我知道該怎么做。
我的問題是我想在一些畫布上繪制圖像。 不管我做什么,似乎繪圖始終與圖像重疊。
問題可能是我在動畫循環中執行此操作,並且某種程度上無法繪制圖像嗎?
您可以在這里看到我的代碼。 (只是很短)。
如您所見,在我的繪制函數中,我繪制了其他東西之后要繪制的圖像。 我通過注釋掉代碼檢查圖像是否正確繪制,嘿,很容易,圖像出現了。 drawImage代碼如下所示:
var drawCanvasImage = new Image();
drawCanvasImage.src = "https://www.w3.org/html/logo/downloads/HTML5_Logo_256.png";
drawCanvasImage.onload = function(){
ctx.drawImage(drawCanvasImage, 0, 0);
}
誰能提供對此的見識? 謝謝。
你應該做這個:
加載所有必要的資源。 圖像,音頻等等。
您可以根據需要顯示“正在加載”消息。
開始繪畫/復制/任何事情。
由於資源可用,因此您可以直接使用它們。
避免在此處load
事件處理程序。
var drawCanvasImage = new Image();
drawCanvasImage.onload = function(){
animFrame(recursiveAnim);
};
drawCanvasImage.src = "myimage";
function drawScreen() {
// ...
ctx.drawImage(drawCanvasImage, 0, 0);
}
var animFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || null ; window.addEventListener('mousemove', saveMove, false); var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); //Global vars var clickX, clickY; //Loops through to draw the graphics mainLoop = function() { drawScreen(); }; //This loops the animation frames var recursiveAnim = function() { mainLoop(); animFrame(recursiveAnim);// }; var drawCanvasImage = new Image(); drawCanvasImage.onload = function(){ animFrame(recursiveAnim); }; drawCanvasImage.src = "https://www.w3.org/html/logo/downloads/HTML5_Logo_256.png"; function drawScreen() { //sky ctx.fillStyle="#33ccff"; ctx.fillRect(0, 0, c.width, c.height); //sun ctx.beginPath(); ctx.arc(680, 150, 90, 10, Math.PI, true); ctx.closePath(); ctx.lineWidth = 5; ctx.fillStyle = '#ffff33'; ctx.fill(); ctx.strokeStyle = '#b2b300'; ctx.stroke(); //grass ctx.beginPath(); ctx.arc(350, 950, 800, 0, Math.PI, true); ctx.closePath(); ctx.lineWidth = 5; ctx.fillStyle = '#3fff00'; ctx.fill(); ctx.strokeStyle = '#1f8000'; ctx.stroke(); ctx.drawImage(drawCanvasImage, 0, 0); //Hey SO, thanks for checking this out! :) } // Mouse click stuff ############################################# { function saveMove(e) { var pos = getMousePos(c, e); clickX = pos.x; clickY = pos.y; } function getMousePos(c, evt) { var rect = c.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top } } }
.title { font-family: "Helvetica", sans-serif; }
<canvas id="myCanvas" width="800" height="300" style="border:1px solid #000000"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.