I am currently developing a whack the mole game using Vanilla JS, and I'm attempting to allow players to choose their own target by uploading an image file. However, despite days of searching for a solution, I have not been successful.
HTML:
<input type='file' id='getval' name="background-image" />
<div class="game">
<div class="hole hole1">
<img class="mole">
</div>
<div class="hole hole2">
<img class="mole">
</div>
</div>
Javascript Vanilla:
document.getElementById('getval').addEventListener('change', readURL);
function readURL() {
let file = document.getElementById("getval").files[0];
document.getElementsByClassName('mole')[0].setAttribute("style", "background-image: url(" + file + ")");
}
CSS:
.mole {
background-image: url('');
}
The game functions properly, but the uploaded image does not display correctly:
https://i.sstatic.net/RkezK.png
If anyone has any insight on how to resolve this issue, I would greatly appreciate it.
This project is part of #javascript30. I modify these projects to practice using Vanilla JS, but I've hit a roadblock with this one.