I have a canvas that I'm able to change the height/width of. Its supposed to display a 2d tile map so I added in the option to enter a world size. After I've entered everything I have an update button that clears the screen and displays the canvas with tiles drawn onto it. The first time I click the update button everything works fine, but after that it stops working, even if I don't change any of the settings. I was wondering if anyone could help me figure out why that is. Thank you in advance.
I've added the canvas into the game using the following Draw Map function:
ClearScreen
html = "<canvas id='gameCanvas'"
html = html + " width='" + ToString(game.canvas_width) + "' height='" + ToString(game.canvas_height) + "' style='border:1px
solid #000000;'>"
html = html + "</canvas>"
msg (html)
JS.drawCanvas()
Here is the JS.drawCanvas() function that I have in a separate .js file:
function drawCanvas() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
const mapWidth = parseInt(document.getElementById("mapWidth").value);
const mapHeight = parseInt(document.getElementById("mapHeight").value);
const worldSize = parseInt(document.getElementById("worldSize").value);
for (var y = 0; y < worldSize; y++) {
for (var x = 0; x < worldSize; x++) {
var rx = x * (mapWidth / worldSize);
var ry = y * (mapHeight / worldSize);
var rw = mapWidth / worldSize;
var rh = mapHeight / worldSize;
ctx.strokeRect(rx, ry, rw, rh);
}
}
}
ClearScreen might hide the previous output (for logging purposes) rather than deleting it. In which case, getElementById will still give you the first one, which might not be visible. I would suggest three possible ways to deal with this:
ctx = $('canvas').filter('#gameCanvas').last().get(0).getContext('2d');
I did the first thing you (@mrangel) listed and I got it to work.
I created the following function and called it before drawing the map:
function delCanvas() {
if (document.getElementById("gameCanvas") != null) {
canvas = document.getElementById("gameCanvas");
canvas.remove()
}
}
Thank you for your help!
I would probably have written it using the jQuery functions for simplicity $('#gameCanvas').remove();
, but I think that's pretty much the same thing. (no need for the if
in the jQuery version, because using its methods on an empty selector will just do nothing).