In the game I have div objects that represent characters, one div has one video child that plays in the loop to represent animated character. Every time something happens on the screen I delete all div objects that represent characters and create them again for each character in the scene. Here is the problem I encountered, when I change one frame for another (I mean here one scene with characters and I change to another that might have different set of characters) the following one doesn't play videos of characters. Not sure if code is helpful in this situation but here some snippets:
//Little part of applyFrame function that controls how objects are represented on the screen
//Here I first delete all character objects from previous frame
//mainFrame is just a background and holds other interactable objects in the game
function applyFrame() {
for (let i = 0; i < mainFrame.children.length; i++) {
mainFrame.children[i].children[0].pause();
mainFrame.removeChild(mainFrame.children[i]);
}
//Then I create for each character new div object and append it a video so I can play animations for characters
//currentFrame is an object that holds all information about how many characters,
//where they positioned, size and video/image src.
for (let i = 0; i < currentFrame.objects.length; i++) {
let elem = document.createElement("div");
mainFrame.appendChild(elem);
mainFrame.children[i].style.opacity = "0";
let video = document.createElement("video");
elem.appendChild(video);
video.classList.add("elemVideo");
//here I just check if there is a video for character otherwise I set a picture
if (currentFrame.objects[i].video != "" || currentFrame.objects[i].video != undefined) {
//here I simply seek for a blob URL to assign it to an element
for (let j = 0; j < animationBlobsGLOB.length; j++) {
if (currentFrame.objects[i].video == animationBlobsGLOB[j].name) {
//assigning a video element src
mainFrame.children[i].children[0].src = animationBlobsGLOB[j].blob;
//playing the video and setting it a loop
video.play();
video.addEventListener("ended", function() {
video.play();
});
}
}
}
}
}
I wonder if that has something to do with deletion of divs that contain videos. Do they also lose their events? Because sometimes I get "Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()" but not always. Also, If I play applyFrame one more videos are playing properly. But I am not sure I want to run this function twice.
Solved, instead of this:
mainFrame.children[i].children[0].src = animationBlobsGLOB[j].blob;
video.play();
video.addEventListener("ended", function() {
video.play();
});
I had to write this:
mainFrame.children[i].children[0].src = animationBlobsGLOB[j].blob;
mainFrame.children[i].children[0].play();
mainFrame.children[i].children[0].addEventListener("ended", function() {
mainFrame.children[i].children[0].play();
});
But I still don't really get why it works that way