MowgliB MowgliB - 9 months ago 32
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.

jsFiddle

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

id
) 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);


Where
id
is some number from 0 to 99,
imgWidth
is the width of each tile and
imgHeight
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?

K3N K3N
Answer Source

One reason to not use jQuery with canvas:

$('canvas').width(imgWidth*10).height(imgHeight*10);

:) 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