MowgliB MowgliB - 1 year ago 50
Javascript Question

Attempting to create a single map image from tiles using canvas element

I have a bunch of png map tiles that I am trying to stitch together on a canvas element.


I am making a 10x10 tile with a counter from 0 to 99 (

) to keep track of where I'm up to. This is the line that plots the image:

ctx.drawImage(this, id%10*imgWidth, Math.floor(id/10)*imgHeight, imgWidth, imgHeight);

is some number from 0 to 99,
is the width of each tile and
is the height of each tile.

I am reasonably confident that should work, but it appears to just plot one stretched tile on the canvas instead of all 100. When I check the console for what was loaded, the images appear to be the correct shape and contents for each tile. The just don't seem to have been placed on the canvas. Does anyone have any ideas?

Answer Source

One reason to not use jQuery with canvas:


:) as this refers to the element size, not the bitmap. I would suggest using instead:

myCanvas.width = imgWidth*10;
myCanvas.height = imgHeight*10;

Modified fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download