I’m trying to create a grid of 10×10 images. These are loaded from javascript (object) and use the onload method to add it to canvas. The adding works, however the canvas images seem to be resized. The result of the currentSizes.cellSize is 80 by the way. However it seems the images added are larger than the 80 defined, even though the drawImage parameters width and height get values 80..
My goals is to built a canvas game as a jQuery plugin. I want to display a javascript-dynamically created grid with islands (just like the web browser conquest type of games). So I want to create a 100% width (and height) canvas where the javascript dynamically measures how big each cell (10×10) has to be..
So I have the following:
for( var i = 0 ; i < totalTiles ; i++ ) {
// go to first column in next row
if( x >= 10 ) {
x = x - 10;
y = y + 1;
}
// build the world
tiles[i] = new Image();
tiles[i].x = x;
tiles[i].y = y;
tiles[i].towidth = currentSizes.cellSize;
tiles[i].toheight = currentSizes.cellSize;
tiles[i].coordx = ( x * currentSizes.cellSize );
tiles[i].coordy = ( y * currentSizes.cellSize );
//tiles[i].onload = function() { canvas2d.drawImage( tiles[i] , 0 , 0 ); }
//tiles[i].onLoad = dibaMethods.drawTile( tiles[i] , ( x * currentSizes.cellSize ) , ( y * currentSizes.cellSize ) , canvas2d );
tiles[i].src = "/images/world/tiles/card5.png";
lastIndex = i;
console.log( "looping at: " + i + " with x/y: " + x + "/" + y + " and coordinates: " + tiles[i].coordx + "/" + tiles[i].coordy );
x++;
}
console.log( "Canvas tiles entered, loaded on DOM load, tiles added: " + tiles.length );
tiles[lastIndex].onload = function() {
for( var i = 0; i < totalTiles ; i++ ) {
canvas2d.drawImage( tiles[i] , tiles[i].coordx , tiles[i].coordy );
//canvas2d.drawImage( tiles[i] , tiles[i].coordx , tiles[i].coordy , tiles[i].towidth , tiles[i].toheight );
}
}
The HTML of the canvas:
<canvas id="world">
</canvas>
Stylesheet:
body { margin: 0; }
canvas#world { clear: both; background: url("/images/world/clouds.jpg") no-repeat; width: 800px; height: 800px; }
You can see how far i got on the url: https://battles.hyn.me/world
Any advice is much appreciated! If the question needs elaborating, please comment!
The issue originated from a canvas element which did not have a width or height attribute.
After editing the html to include these attributes and removing the stylesheet entries it finally worked.
So bottomline, always add a width and height attribute to the canvas element.