I followed a tutorial on how to build basic games by using JS/HTML and now I am expanding it. Game here
press space to fire
press the right arrow to turn right and the left one to turn left
I was able to get the location of the collision between an enemy and a missile and add a new #explosion to the html by using innerHTML. I am confused how I can be able to remove the explosion after 1 second.
const explosion = (topEn, leftEn) => {
document.getElementById('explosions').innerHTML +=
`
<div id="explosion" style='
left:${leftEn}px;
top: ${topEn}px;
'></div>
`;
}
#explosion{
background-image: url("assets/explosion.png");
height: 50px;
width: 50px;
position: absolute;
}
Without the rest of your code it's hard to give you an exact show, but this is largely what my comment was referring to.
const explosion = (topEn, leftEn, delay = 1000) => {
const div = document.createElement('div');
div.id = 'explosion';
div.style.top = topEn + 'px';
div.style.left = leftEn + 'px';
document.getElementById('explosions').append(div);
setTimeout(() => {
div.remove()
}, delay);
}
explosion(200, 200, 1000);
setTimeout(()=> explosion(300, 400, 800), 500)
#explosion {
background-image: url("assets/explosion.png");
height: 50px;
width: 50px;
position: absolute;
/* I added this to be able to see the divs*/
background-color: red;
}
body, html, #explosions {
height: 100%;
width: 100%;
}
<div id="explosions"></div>
Notes:
If you are going to perhaps have multiple elements of the same type (i.e.) explosions in the DOM at the same time you should move to using a class instead of an ID. IDs are unique identifiers, so while you can have multiple elements with the same ID, it will lead you to unexpected results. If your game will be able to have more than 1 explosion going at any given time, move #explosion to .explosion
Related
I am trying to do an animation example but there is a problem about accumulation. At first click on the button, the translate animation is done and the position of the element changes permanently. However, on second click it does the translate animation again but this time does not keep the last position. How to overcome this? I went through MDN document and applied the optional section but failed to complete this challenge. Regards,
https://jsfiddle.net/ja218pbr/19/
document.getElementsByTagName("button")[0].addEventListener("click", function() {
document.querySelectorAll("div")[0].animate([
{transform: 'translate(100%, 0)'}
], {
duration: 250,
composite: "accumulate",
iterationComposite: "accumulate",
fill: "forwards"
});
});
If I'm understanding this correctly, you want to be able to let the object slide again from the position it ended in earlier. To do this we can get the boundingClientRect each time the button is clicked and calculate the new translation distance by basically taking the width of the object and adding the left distance of the client rect, this will effectively allow the rectangle to keep moving from the distance it ended in before. Also I removed the composite property because it caused the rectangle to jump over the correct position.
document.getElementsByTagName("button")[0].addEventListener("click", function() {
const clientRect = document.querySelectorAll("div")[0].getBoundingClientRect();
const translationX = clientRect.width + clientRect.left;
document.querySelectorAll("div")[0].animate([{
transform: `translate(${translationX}px, 0)`
}], {
duration: 250,
iterationComposite: "accumulate",
fill: "forwards"
});
});
body {
margin: 0;
}
div {
position: relative;
height: 150px;
width: 150px;
background-color: yellow;
text-align: center;
line-height: 150px;
}
<div>Moving Object</div>
<button>Press</button>
I decided to make a Pac-Man game and after I did it and everything was working somewhat fine on local document I pushed my website on Github pages and decrease in fps was enormous. It turned out page was making recalculation for hundreds elements which caused 20ms+ delay.
Here's a small part of the code that still has performance difference between local and github-pages hosted website.
const gameBoard = document.getElementById("game-board");
const root = document.documentElement.style;
let elements;
let characterNode;
let position = 658;
makeLevel();
function makeLevel() {
for (let i = 0; i < 868; i++) {
const element = document.createElement("DIV");
element.style.backgroundPosition = `0 0`;
let character = document.createElement("DIV");
character.className = "yellow";
element.append(character);
gameBoard.append(element);
}
elements = Array.from(gameBoard.children);
characterNode = elements[658].children[0];
changePosition();
}
function changePosition() {
root.setProperty(`--yellow-sprite-y`, `-32px`);
characterNode.style.transform = `translateX(-20px)`;
setTimeout(() => {
characterNode.style.transform = "";
characterNode.classList.remove(`yellow-visible`);
position = position - 1;
characterNode = elements[position].children[0];
characterNode.classList.add(`yellow-visible`);
changePosition()
}, 200)
}
:root {
--yellow-sprite-y: -32px;
}
#game-board {
width: 560px;
height: 620px;
display: grid;
grid-template-columns: repeat(28, 20px);
background-color: #000000;
}
#game-board > * {
position: relative;
width: 20px;
height: 20px;
}
.yellow {
position: absolute;
top: -4px;
left: -5.5px;
width: 30px;
height: 28px;
z-index: 10;
}
.yellow-visible {
background-image: url("https://i.imgur.com/SphNpH6.png");
background-position: -32px var(--yellow-sprite-y);
transition: transform 200ms linear;
}
<div id="game-board">
</div>
The exact problem in this code is line 29 which on local document performs like this:
while after hosting it on Github performs this way:
Why is it working this way and what can I do to lessen the performance decrease on hosted page?
Amazingly everything works well and bug doesn't exist on CodePen, yet on Github it still persists.
After getting some feedback that my site works well for other users I shared it on CodePen and it also worked fine, day later somebody said there could be an extension that could do something like that and indeed Adblocker Ultimate caused the slow performance.
I'm trying to make a website which will keep on adding video players to the page as the page is being scrolled down. Though I have some concerns that large amount of video players on a page can cause lag on the website and cause the website to slow down. I think I have experienced slow down during some tests of my website. So is it possible to detect whether the website is being slowed down due of the amount of elements on the web and so I can start deleting the video elements from the top of the page?
index.html:
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
timeout = undefined;
for (var x=0;x<50;x++) {
var video = document.createElement("video");
video.style.backgroundColor = "orange";
video.poster = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Big_buck_bunny_poster_big.jpg/220px-Big_buck_bunny_poster_big.jpg";
video.src = "https://dash.akamaized.net/akamai/bbb/bbb_3840x2160_60fps_18000k.mp4";
video.controls = true;
content.appendChild(video);
}
window.addEventListener("scroll", function () {
var $this = this;
window.clearTimeout(timeout);
timeout = setTimeout(function() {
var content_margin_top = $this.innerHeight * 0.11;
var last_player = content.children[content.querySelectorAll("video").length - 1];
if (last_player.offsetTop - content_margin_top <= $this.scrollY) {
for (var x=0;x<10;x++) {
var video = document.createElement("video");
video.style.backgroundColor = "orange";
video.poster = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Big_buck_bunny_poster_big.jpg/220px-Big_buck_bunny_poster_big.jpg";
video.src = "https://dash.akamaized.net/akamai/bbb/bbb_3840x2160_60fps_18000k.mp4";
video.controls = true;
content.appendChild(video);
}
}
}, 250);
});
body {
margin: 0;
}
#nav {
width: 100%;
height: 10%;
position: absolute;
top: 0;
background-color: rgb(108, 171, 247);
}
#content {
height: 100%;
width: 98%;
position: absolute;
top: 11%;
left: 1%;
}
video {
width: 100%;
height: 75%;
border: 1px solid black;
}
<html>
<head>
<title></title>
</head>
<body>
<div id="nav"></div>
<div id="content"></div>
</body>
</html>
I would think about the issue in a slightly different way: What should I do to make that page work as fast as possible, downloading as little data as possible and render only necessary containers when needed?
My recommendations:
1) Don't append and init video containers on during scroll. Render only thumbnails for future video containers using img tags. Making lazy loading for these images should be considered as well. Add "play" button to the center of preview container. Once user clicks on the button - render video tag with a proper src and play it.
2) Don't use a scroll event listener to detect containers offsets and lazy loading. Use Intersection API instead.
I am currently learning JavaScript and all the solutions that I've come across use the jQuery library. Is there a way to do it, just using pure JavaScript?
The idea is to have something like:
function passed(element) {if passed: do something}
Listen for the scroll event. To find the current scroll position, you can call the scollY method.
To get the Y coordinate of the top of an element, you can use the element's offsetTop. Because the element has a height, we want to add the height to our calculation.
That's it.
window.addEventListener("scroll", function() {
var elementTarget = document.getElementById("section-2");
if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
alert("You've scrolled past the second div");
}
});
.section-1 {
height: 400px;
width: 100%;
background: green;
}
.section-3 {
height: 400px;
width: 100%;
background: orange;
}
<div class="section-1"></div>
<div id="section-2">Scroll past this div</div>
<div class="section-3"></div>
You should be able to use the following:
if(window.scrollY >(element.offsetHeight + element.offsetTop)){
// do something
}
With https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop you can get the Y coordinate of an element.
With https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY you can get the current Y coordinate of the scroll.
With https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight you get the height of an element.
So the only thing that remains to do is to check if scrollY > (offsetHeight + offsetTop). If this is true, you passed the element with the scroll.
I leave to you the implementation, as a practice to learn Javascript ;)
if (element.getBoundingClientRect().y < 0) {
// do something
}
This can be achieved with the IntersectionObserver API without having to rely on scroll events at all.
const elementTarget = document.getElementById("section-2");
// skip first callback when first observing
let firstCallback = true;
const observer = new IntersectionObserver(entries => {
if (!entries[0].isIntersecting) {
if (firstCallback) {
firstCallback = false;
} else {
alert("You've scrolled past the second div");
}
}
});
observer.observe(elementTarget);
// remember to unobserve when done
.section-1 {
height: 1000px;
width: 100%;
background: green;
}
.section-3 {
height: 1000px;
width: 100%;
background: orange;
}
<div class="section-1"></div>
<div id="section-2">Scroll past this div</div>
<div class="section-3"></div>
Unfortunately 100vh is not always the same as 100% browser height as can be shown in the following example.
html,
body {
height: 100%;
}
body {
overflow: scroll;
}
.vh {
background-color: blue;
float: left;
height: 50vh;
width: 100px;
}
.pc {
background-color: green;
float: left;
height: 50%;
width: 100px;
}
<div class="vh"></div>
<div class="pc"></div>
The issue is more pronounced on iPhone 6+ with how the upper location bar and lower navigation bar expand and contract on scroll, but are not included in the calculation for 100vh.
The actual value of 100% height can be acquired by using window.innerHeight in JS.
Is there a convenient way to calculate the current conversion of 100vh to pixels in JS?
I'm trying to avoid needing to generate dummy elements with inline styles just to calculate 100vh.
For purposes of this question, assume a hostile environment where max-width or max-height may be producing incorrect values, and there isn't an existing element with 100vh anywhere on the page. Basically, assume that anything that can go wrong has with the exception of native browser functions, which are guaranteed to be clean.
The best I've come up with so far is:
function vh() {
var div,
h;
div = document.createElement('div');
div.style.height = '100vh';
div.style.maxHeight = 'none';
div.style.boxSizing = 'content-box';
document.body.appendChild(div);
h = div.clientHeight;
document.body.removeChild(div);
return h;
}
but it seems far too verbose for calculating the current value for 100vh, and I'm not sure if there are other issues with it.
How about:
function viewportToPixels(value) {
var parts = value.match(/([0-9\.]+)(vh|vw)/)
var q = Number(parts[1])
var side = window[['innerHeight', 'innerWidth'][['vh', 'vw'].indexOf(parts[2])]]
return side * (q/100)
}
Usage:
viewportToPixels('100vh') // window.innerHeight
viewportToPixels('50vw') // window.innerWidth / 2
The difference comes from the scrollbar scrollbar.
You'll need to add the height of the scrollbar to the window.innerHeight. There doesn't seem to be a super solid way of doing this, per this other question:
Getting scroll bar width using JavaScript