簡體   English   中英

將圖像加載到 HTML5 Canvas

[英]Loading image onto HTML5 Canvas

我正在關注使用 HTML5 和 JavaScript 構建游戲的過時教程。 我過去曾與 JavaScript 合作過,但 canvas 對我來說是新的。 我嘗試運行的代碼似乎相當簡單,但似乎 HTML5 自本教程發布以來發生了變化,我無法加載圖像。

我已經進行了一些研究,並且能夠通過在將其繪制到 canvas之前首先確保它已加載來正確加載圖像。 這很簡單,但現在我不太確定如何調整更深入的代碼來適應這種情況。

給定以下代碼,我需要如何以及在哪里確保在繪制圖像之前先加載圖像。 我面臨的主要問題是在哪里放置代碼以等待加載以及如何確保徽標實用程序 object 在下面的代碼中可用。

var phrase = "Click or tap the screen to start the game";

    // Clear the canvas
    c.clearRect (0, 0, canvas.width, canvas.height);

    var logoImg = new Image();
    logoImg.src = '../img/logo.png';

    // Store the original width value so that we can keep the same width/height ratio later
    var originalWidth = logoImg.width;

    // Compute the new width and height values
    logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
    logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);

    // Create an small utility object
    var logo = {
        img: logoImg,
        x: (canvas.width/2) - (logoImg.width/2),
        y: (canvas.height/2) - (logoImg.height/2)
    }

    // Present the image
    c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);

    // Change the color to black
    c.fillStyle = '#000000';
    c.font = 'bold 16px Arial, sans-serif';

    var textSize = c.measureText (phrase);
    var xCoord = (canvas.width / 2) - (textSize.width / 2);

    c.fillText (phrase, xCoord, (logo.y + logo.img.height) + 50);

多虧了 YosefTukachinsky 的神秘建議,才弄明白。

var logoImg = new Image();
logoImg.src = '../img/logo.png';

logoImg.onload = function(){ 
     // Store the original width value so that we can keep the same width/height ratio later
     var originalWidth = logoImg.width;

     // Compute the new width and height values
     logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
     logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);

     // Create an small utility object
     var logo = {
          img: logoImg,
          x: (canvas.width/2) - (logoImg.width/2),
          y: (canvas.height/2) - (logoImg.height/2)
     }

     // Present the image
     c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);

     // Change the color to black
     c.fillStyle = '#000000';
     c.font = 'bold 16px Arial, sans-serif';

     var textSize = c.measureText (phrase);
     var xCoord = (canvas.width / 2) - (textSize.width / 2);

     c.fillText (phrase, xCoord, (logo.y + logo.img.height) + 50);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM