Note that there are some explanatory texts on larger screens.

plurals
  1. POHTML5 drawing pictures on a canvas with a for loop?
    primarykey
    data
    text
    <p>So, I want to create a minecraft website theme using HTML5. I am a bit shaky in HTML5/Javascript(haven't used it in a while), and I need some help. I am trying to calculate a number of 16x16px tiles that can fit on the screen. Then, randomly "generate a map" for the background of the screen. Then, I use the same 2 for loops that generate the map to fill the screen with the tiles(which are assigned picture paths during the generation process). The problem is, the canvas is completely white. Can anyone pick out the problem, and give me any tips if possible? Thanks in advance! Here is my HTML5 code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Minecraft Background Check&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="bg" style="position:fixed; top:0; left:0; border:1px solid #c3c3c3; width: 100%; height: 100%;"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; "use strict"; var c = document.getElementById("bg"); var ctx = c.getContext("2d"); ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; var width = Math.ceil(window.innerWidth / 16); var height = Math.ceil(window.innerHeight / 16); for (var x=0;x&lt;width;x++) { for(var y=0;y&lt;height;y++) { var rand = Math.floor(Math.random()*11); var texLoc = getImageNameFromRand(rand,y,height); var img=new Image(); img.onload = function(){ return function() { ctx.drawImage(img,x*16,y*16); }; }; img.src=texLoc; } } function getImageNameFromRand(rand,yVal,maxY) { var dirt = 'dirt.png'; var stone = 'stone.png'; var cobble = 'cobble.png'; var mosscobble = 'mosscobble.png'; var bedrock = 'bedrock.png'; if(yVal===0) { return dirt; } else if(yVal&lt;3) { if(rand &lt; 7) { return dirt; } else { return stone; } } else if(yVal&lt;5) { if(rand &lt; 4) { return dirt; } else { return stone; } } else if(yVal&lt;maxY-2) { if(rand === 0) { return dirt; } else if(rand &lt; 4) { return cobble; } else if(rand &lt; 5) { return mosscobble; } else { return stone; } } else if(yVal&lt;maxY-1) { if(rand &lt; 4) { return bedrock; } else { return stone; } } else if(yVal&lt;maxY) { if(rand &lt; 7) { return bedrock; } else { return stone; } } else { return bedrock; } return bedrock; } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload