I'm trying to create a grid of a specific height/width given input. If I hard code in the height and width in the canvas below (10 and 5 in this case) it works perfectly
const canvasWindow = document.getElementById("canvas-window")
const height = document.getElementById("height")
const width = document.getElementById("width")
const generateCanvasBtn = document.getElementById("generate-canvas-btn")
generateCanvasBtn.addEventListener("click", () => {
const canvas = new Canvas(document.getElementById("canvas-window"), 10, 5);
canvas.generateCanvas();
})
This example breaks though:
const canvasWindow = document.getElementById("canvas-window")
const height = document.getElementById("height")
const width = document.getElementById("width")
const generateCanvasBtn = document.getElementById("generate-canvas-btn")
generateCanvasBtn.addEventListener("click", () => {
const canvas = new Canvas(document.getElementById("canvas-window"), height.value, width.value);
canvas.generateCanvas();
})
Any ideas what could be causing this? If I log height.value and width.value it is getting the values just fine, so I'm struggling to see how it's any different than being hardcoded if the values are being read in fine? The error I'm getting is:
canvas.js:18 Uncaught TypeError: Cannot set properties of undefined (setting '0') at Canvas.generateCanvas (canvas.js:18:33) at HTMLInputElement. (pixelcreator.js:8:12)
Here is code containing the line that the error references:
class Canvas {
grid;
constructor(window, height, width) {
this.window = window;
this.height = height;
this.width = width;
}
generateCanvas() {
this.grid = new Array(this.height).fill(0).map(() => new Array(this.width).fill(0));
for (let i = 0; i < this.height; i ) {
const row = document.createElement("div");
row.classList.add('row');
this.window.appendChild(row);
for (let j = 0; j < this.width; j ) {
this.grid[i][j] = new Cell(row) // this is line 18 from the error
this.grid[i][j].createCell();
}
}
}
CodePudding user response:
height.value
or width.value
might be a string type.
Try this:
new Canvas(document.getElementById("canvas-window"), parseInt(height.value), parseInt(width.value));
CodePudding user response:
You are using the value of the input directly which is a string. Try parsing it to an integer with parseInt(...)
const canvasWindow = document.getElementById("canvas-window")
const height = document.getElementById("height")
const width = document.getElementById("width")
const generateCanvasBtn = document.getElementById("generate-canvas-btn")
generateCanvasBtn.addEventListener("click", () => {
const canvas = new Canvas(document.getElementById("canvas-window"), parseInt(height.value), parseInt(width.value));
canvas.generateCanvas();
})