Reputation: 21
I am trying to do a pac-man game and my code of the function for adding layout on the board looks like this:
for (let i = 0; i < layout.length; i++) {
const square = document.createElement('div')
grid.appendChild(square)
squares.push(square)
// add layout to the board //
if (layout[i] === 0) {
squares[i].classList.add('pac-dot')
} else if (layout[i] === 1) {
squares[i].classList.add('wall')
} else if (layout[i] === 3) {
squares[i].classList.add('strawberry')
}
}
I want to add an image to the squares in the classList Strawberry
I tried creating a div on html and styling it with css but that didn't work out. I also tried the img
tag with an id but it also did not work out.
How can I add an image to the squares?
Thanks for the help!
Upvotes: 1
Views: 327
Reputation: 21
I solved the problem with adding another function to the JS body like this:
function addImageToSquare(div, imgSource, height, width) {
let img = document.createElement("img");
img.src = imgSource
img.id = "picture"
img.style.height = "25px"
img.style.width = "25px"
div.appendChild(img);
}
And I called the function with this
addImageToSquare(squares[i], "images/strawberry.png")
under
else if (layout[i] === 3) {
squares[i].classList.add('strawberry')
Upvotes: 1
Reputation: 60
In strawberry class put a css style called background image
.strawberry {
background-image: url("");
/*
put image url in the url ("")
any url will work ex. images/myimage.jpg or www.web/image.jpg
*/
}
Upvotes: 0