Right now, I am engaged in a process that involves:
- creating a canvas and attaching it to a division
- applying a background image through CSS to that canvas.
- drawing a hex grid on the canvas
- placing PNGs on the canvas.
- animating those PNGs to show "movement".
Unfortunately, constantly redrawing the entire canvas, including the stationary PNGs, is becoming cumbersome.
I am considering whether it would be more efficient to have a single canvas for the background/hex grid and generate the PNGs on additional, smaller canvas elements which are then layered on top of the background canvas using zIndex. This approach could simplify the animations (moving PNGs).
However, I am facing difficulties when it comes to accurately positioning the "new" canvases at the correct x/y coordinates relative to the background canvas.
this.drawShipImage = function(name, id, x, y){
var div = document.getElementById("grid");
// the initial large canvas with background is created elsewhere but has the same width/height as "grid"
var canvas = document.createElement("canvas");
canvas.id = name + id;
canvas.width = 30;
canvas.height = 30;
canvas.style.position = "absolute";
canvas.style.zIndex = 1;
var context = canvas.getContext("2d");
context.scale(0.75, 0.75);
context.drawImage(ship, 0, 0);
div.appendChild(canvas);
}
This function essentially requires two key parameters, namely the x/y values where the new canvas should be positioned in relation to the width/height of the background canvas. I am currently unable to find a solution to ensure that the image appears at the correct coordinates.
It seems like the only way it could potentially work is by adding canvas.style.margin = x/y-ish into the equation ?