Reputation: 79
I would like a picture to appear x number of times in rows and columns. So if I'm creating a multiplication game and the question is "What is 9 x 5?", how do I ensure my 200x200 photo appears 45 times in 9 columns and 5 rows using vanilla JS? I figure I need to make a table, but don't know how to do that based on what the two numbers are.
let one = Math.floor(Math.random() * 9) + 1;
let two = Math.floor(Math.random() * 9) + 1;
let photos = document.getElementById('photos');
let product = one * two;
let productNum = parseInt(product);
const img = new Image();
const imgSrc = x.jpg;
function generateImage() {
const img = document.createElement('img')
img.src = imgSrc;
return img;
}
for (let i = 0; i < productNum; i++ ) {
photos.appendChild(generateImage());
}
Upvotes: 1
Views: 497
Reputation: 629
The easiest way would probably be to create a div for each row and add images to each row to make up the columns.
let one = Math.floor(Math.random() * 9) + 1;
let two = Math.floor(Math.random() * 9) + 1;
let photos = document.getElementById("photos");
let product = one * two;
let productNum = parseInt(product);
const imgSrc = "https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196";
function generateImage() {
const img = document.createElement("img");
img.src = imgSrc;
return img;
}
const rows = one;
const columns = two;
for (let i = 0; i < rows; i++) {
const rowDiv = document.createElement("div");
for (let j = 0; j < columns; j++) {
rowDiv.appendChild(generateImage());
}
photos.appendChild(rowDiv);
}
<div id="photos"></div>
Upvotes: 1
Reputation: 613
You could create a function like this:
function createTable(w, h, src) {
let table = document.createElement('table');
for(let i = 0; i < h; ++i) {
let row = table.insertRow();
for(let j = 0; j < w; ++j) {
let td = row.insertCell();
let img = document.createElement('img');
img.setAttribute('src', src);
td.appendChild(img);
}
}
document.getElementById('photos').appendChild(table);
}
createTable(9, 5, 'https://i.imgur.com/DfEE9nm.png');
<html>
<body>
<div id='photos'></div>
</body>
</html>
Upvotes: 2