I'm using JavaScript to create a stack of 16 boxes. I don't think I have the makeBox() function in the right place.
let makeBox = function() {
let box = document.createElement('div');
document.body.appendChild(box);
box.style.width = '28px';
box.style.height = '28px';
box.style.border = '1px solid black';
return box;
};
let makeGrid = function(numberOfRows) {
let y = 0;
let x = 0;
while (y < numberOfRows) {
x = 0;
while (x < numberOfRows) {
x = x + 1;
}
y = y + 1;
}
makeBox();
};
makeGrid(16);
I'm just getting one box in the browser. If anyone has any experience with this, if they could please help.
If you want to make a grid of boxes CSS Grid can help. It saves effort on creating nested loops. Just loop from 0 to the number passed in as the argument multiplied that same number, and create a box on each iteration. Then add it to the element that's been set up to control the grid.
I would also use a class for the box too.
function makeBox(x) {
const box = document.createElement('div');
box.classList.add('box');
box.textContent = x;
return box;
};
// The grid will be the argument (a number)
// multiplied by that number again, so you just need
// to loop from 0 to that number
function makeGrid(n) {
const grid = document.querySelector('#grid');
for (let x = 0; x < n * n; x++) {
grid.appendChild(makeBox(x));
}
};
makeGrid(16);
#grid { display: grid; grid-template-columns: repeat(16, 1fr); gap: 2px; }
.box { width: 28px; height: 28px; border: 1px solid black; text-align: center; }
<div id="grid"></div>
I have a large background image and some much smaller images for the user to drag around on the background. I need this to be efficient in terms of performance, so i'm trying to avoid libraries. I'm fine with drag 'n' drop if it work's well, but im trying to get drag.
Im pretty much trying to do this. But after 8 years there must be a cleaner way to do this right?
I currently have a drag 'n' drop system that almost works, but when i drop the smaller images, they are just a little off and it's very annoying. Is there a way to fix my code, or do i need to take a whole different approach?
This is my code so far:
var draggedPoint;
function dragStart(event) {
draggedPoint = event.target; // my global var
}
function drop(event) {
event.preventDefault();
let xDiff = draggedPoint.x - event.pageX;
let yDiff = draggedPoint.y - event.pageY;
let left = draggedPoint.style.marginLeft; // get margins
let top = draggedPoint.style.marginTop;
let leftNum = Number(left.substring(0, left.length - 2)); // cut off px from the end
let topNum = Number(top.substring(0, top.length - 2));
let newLeft = leftNum - xDiff + "px" // count new margins and put px back to the end
let newTop = topNum - yDiff + "px"
draggedPoint.style.marginLeft = newLeft;
draggedPoint.style.marginTop = newTop;
}
function allowDrop(event) {
event.preventDefault();
}
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.style.marginLeft = `${Math.floor(Math.random() * 900)}px`
sensor.style.marginTop = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = function() {
sensorClick(logs[i].id)
};
sensor.addEventListener("dragstart", dragStart, null);
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
<!-- my html: -->
<style>
.map {
width: 900px;
height: 500px;
align-content: center;
margin: 150px auto 150px auto;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<div class="map" onDrop="drop(event)" ondragover="allowDrop(event)">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false">
<div>
With the answers from here and some time i was able to get a smooth drag and click with pure js.
Here is a JSFiddle to see it in action.
let maxLeft;
let maxTop;
const minLeft = 0;
const minTop = 0;
let timeDelta;
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
var originalX;
var originalY;
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function sensorClick () {
if (Date.now() - timeDelta < 150) { // check that we didn't drag
createPopup(this);
}
}
// create a popup when we click
function createPopup(parent) {
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
let popup = document.createElement("div");
popup.id = "popup";
popup.className = "popup";
popup.style.top = parent.y - 110 + "px";
popup.style.left = parent.x - 75 + "px";
let text = document.createElement("span");
text.textContent = parent.id;
popup.appendChild(text);
var map = document.getElementsByClassName("map")[0];
map.appendChild(popup);
}
// when our base is loaded
function baseOnLoad() {
var map = document.getElementsByClassName("map")[0];
let base = document.getElementsByClassName("base")[0];
maxLeft = base.width - 50;
maxTop = base.height - 50;
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.id = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.classList.add("dragme");
sensor.style.left = `${Math.floor(Math.random() * 900)}px`
sensor.style.top = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = sensorClick;
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
}
function startDrag(e) {
timeDelta = Date.now(); // get current millis
// determine event object
if (!e) var e = window.event;
// prevent default event
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
originalX = targ.style.left;
originalY = targ.style.top;
// check that this is a draggable element
if (!targ.classList.contains('dragme')) return;
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// calculate integer values for top and left properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
document.onmousemove = dragDiv; // move div element
return false; // prevent default event
}
function dragDiv(e) {
if (!drag) return;
if (!e) var e = window.event;
// move div element and check for borders
let newLeft = coordX + e.clientX - offsetX;
if (newLeft < maxLeft && newLeft > minLeft) targ.style.left = newLeft + 'px'
let newTop = coordY + e.clientY - offsetY;
if (newTop < maxTop && newTop > minTop) targ.style.top = newTop + 'px'
return false; // prevent default event
}
function stopDrag() {
if (typeof drag == "undefined") return;
if (drag) {
if (Date.now() - timeDelta > 150) { // we dragged
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
} else {
targ.style.left = originalX;
targ.style.top = originalY;
}
}
drag = false;
}
.map {
width: 900px;
height: 500px;
margin: 50px
position: relative;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
}
.dragme {
cursor: move;
left: 0px;
top: 0px;
}
.popup {
position: absolute;
display: inline-block;
width: 200px;
height: 100px;
background-color: #9FC990;
border-radius: 10%;
}
.popup::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #9FC990 transparent transparent transparent;
}
.popup span {
width: 90%;
margin: 10px;
display: inline-block;
text-align: center;
}
<div class="map" width="950px" height="500px">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false" onload="baseOnLoad()">
<div>
why my checkCollision function is not working in foreach loop ? I want to check whether obs (obstacle) is hits/overlaps on collector (gray object). I am checking every 1 millisecond using setInterval checkCollision function. Basically I am trying to build a simple car game. please help me and thank you in advance
let body = document.body[0];
let container = document.querySelector(".container");
let allObstacles = [];
let colors = ["green", "green", "red"];
let collector = document.getElementById("collector");
class Obstacle {
constructor(yPos) {
this.yPos = -50;
}
randomnum() {
let randX = Math.floor(Math.random() * (container.clientWidth - 50));
return randX;
}
createObstacle() {
let obstacle = document.createElement("div");
obstacle.classList.add("obstacle");
let bgColor = colors[Math.floor(Math.random() * colors.length)];
obstacle.style.width = "50px";
obstacle.style.height = "50px";
obstacle.style.position = "absolute";
obstacle.style.left = this.randomnum() + "px";
obstacle.style.top = this.yPos + "px";
obstacle.style.backgroundColor = bgColor;
obstacle.dataset.behave = bgColor;
container.appendChild(obstacle);
return obstacle;
}
element = this.createObstacle();
updatePosition() {
this.yPos += 2;
this.element.style.top = this.yPos + "px";
}
kill() {
this.element.remove();
}
}
let dropObs = setInterval(function() {
allObstacles.forEach(function(obs) {
obs.updatePosition();
});
allObstacles.forEach(function(obs) {
// why checkCollision function is not working?
if (checkCollision(obs, collector)) {
console.log("hit");
}
if (obs.yPos > container.clientHeight) {
obs.kill();
}
});
}, 10);
let generateObs = setInterval(function() {
let obs = new Obstacle();
allObstacles.push(obs);
}, 2000);
function checkCollision(obj1, obj2) {
var obj1Y = obj1.offsetTop;
var obj2Y = obj2.offsetTop;
var obj1X = obj1.offsetLeft;
var obj2X = obj2.offsetLeft;
if (
obj2Y + 100 >= obj1Y &&
obj2Y <= obj1Y + 100 &&
obj2X + 100 >= obj1X &&
obj2X <= obj1X + 100
) {
return 1;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
}
html,
body {
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
#collector {
width: 50px;
height: 100px;
background: gray;
position: absolute;
top: calc(100vh - 100px);
left: 50%;
margin-left: -25px;
}
<div class="container">
<div id="collector"></div>
</div>
The first thing you should not use setInterval for this type of animation. Use requestAnimationFrame
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
obj1X,obj1Y comming undefined.
Ok I'm trying to add every one second a 1% width with a background colour, but it appears in oneblock...
Can someone help me ?
Thank you all
Here is my code :
setTimeout(function() {
var percentage = 1;
for (var i = 0; i < 10; i++) {
var blabla = i + percentage
console.log(blabla)
document.getElementById("position").style.width = blabla + "%";
document.getElementById("position").style.backgroundColor = "blue";
document.getElementById("position").style.height = "20px";
}
}, 1000);
}
Rather than a loop, use setInterval
const increment = 1;
const tick = 1000;
let percent = 0;
const timer = setInterval(() => {
const div = document.querySelector('#position');
percent += increment;
div.style.width = `${percent}%`;
if ( percent >= 100 ) clearInterval(timer);
}, tick);
#position {
background-color: blue;
height: 20px;
width: 1%;
}
<div id="position"></div>
Maybe lets do this for several progress bars.
const timers = [];
const doTimer = (id, { tick = 1000, increment = 1 } = {}) => {
let percent = 0;
timers[id] = setInterval(() => {
const div = document.querySelector(`#${id}`);
percent += increment;
div.style.width = `${percent}%`;
div.innerHTML = `${percent}%`;
if ( percent >= 100 ) clearInterval(timers[id]);
}, tick);
};
doTimer('position');
doTimer('data', { tick: 500 });
doTimer('another', { increment: 5 });
#position, #data, #another {
background-color: blue;
height: 20px;
width: 1%;
}
#data {
background-color: red;
}
#another {
background-color: yellow;
}
<div id="position"></div>
<div id="data"></div>
<div id="another"></div>
document.getElementById("position").style.backgroundColor = "blue";
var i = 0;
function loop(){
i++;
document.getElementById("position").style.width = i+"%";
document.getElementById("position").innerHTML = i+"%";
if(i<10) {
setTimeout(function() {
loop();
}, 1000);
}
}
loop();
<div id="position"></div>
So I'm making a Tetris game and right now I'm trying to clear a row when each square is filled by a tetromino piece. So far I am able to determine if that row is filled up using the every() method on the row. It looks like this
function checkForPoints() {
for(let r = 0; r < row; r++) {
if(board[r].every(squareCheck)) {
alert('yo');
board[r].every(clearSquare);
}
}
function squareCheck(sq) {
if(sq !== vacant) return true;
else return false;
}
function clearSquare(sq) {
sq = vacant;
}
}
If every square in the row is filled up then the condition is true and it should proceed to make all squares black or vacant in this case. However this doesn't happen. I have no clue why? My every() method works in determining if every square is not vacant, but that same method won't work in changing that array's elements to equal "black" or vacant?
// //create your globals
// const canvas = document.querySelector('#canvas');
// const ctx = canvas.getContext('2d');
// const row = 20;
// const col = 10;
// const sq = 40;
// const vacant = 'black';
// //-----------------------Why can't I initialize the tetrominos??
// //create and draw board
// let board = [];
// for(let r = 0; r < row; r++) {
// board[r] = [];
// for(let c = 0; c < col; c++) {
// board[r][c] = vacant;
// draw(c, r, board[r][c]);
// }
// }
// //define a function to draw to the canvas
// function draw(x, y, color) {
// ctx.fillStyle = color;
// ctx.fillRect(x * sq, y * sq, sq, sq);
// ctx.strokeStyle = 'white';
// ctx.strokeRect(x * sq, y * sq, sq, sq);
// }
// //create an object for the tetrominos
// function Tetromino(tetromino, color) {
// this.tetromino = tetromino;
// this.color = color;
// this.tetrominoN = 0;
// this.activeTetromino = this.tetromino[this.tetrominoN];
// this.x = 0;
// this.y = 0;
// }
// //create an array for the pieces
// const pieces = [
// [Z, 'red'],
// [S, 'limegreen'],
// [T, 'yellow'],
// [O, 'blue'],
// [L, '#b938ff'],
// [I, 'cyan'],
// [J, 'orange']
// ]
// //create a new instance of Tetromino
// function randomPiece() {
// let r = Math.floor(Math.random() * pieces.length);
// return new Tetromino(pieces[r][0], pieces[r][1]);
// }
// let p = randomPiece();
// //draw the piece
// function drawPiece(piece) {
// //loop through the tetromino
// for(let r = 0; r < piece.length; r++) {
// for(let c = 0; c < piece.length; c++) {
// //if the tetromino index is zero skip it
// if(!piece[r][c]) continue;
// //else draw it
// else draw(p.x + c, p.y + r, p.color);
// }
// }
// }
// //undrawdraw the piece
// function undrawPiece(piece) {
// //loop through the tetromino
// for(let r = 0; r < piece.length; r++) {
// for(let c = 0; c < piece.length; c++) {
// //if the tetromino index is zero skip it
// if(!piece[r][c]) continue;
// //else draw it
// else draw(p.x + c, p.y + r, vacant);
// }
// }
// }
// drawPiece(p.activeTetromino);
// //control the piece
// document.addEventListener('keydown', (event) => {
// if(event.keyCode === 37) p.moveLeft();
// else if (event.keyCode === 38) p.rotate();
// else if (event.keyCode === 39) p.moveRight();
// else if (event.keyCode === 40) p.moveDown();
// });
// Tetromino.prototype.moveDown = function() {
// if(!this.collision(0, 1, this.activeTetromino)) {
// undrawPiece(this.activeTetromino);
// this.y++;
// drawPiece(this.activeTetromino);
// } else {
// //lock piece and generate a new one
// this.lock();
// p = randomPiece();
// }
// }
// Tetromino.prototype.moveLeft = function() {
// if(!this.collision(-1, 0, this.activeTetromino)) {
// undrawPiece(this.activeTetromino);
// this.x--;
// drawPiece(this.activeTetromino);
// }
// }
// Tetromino.prototype.moveRight = function() {
// if(!this.collision(1, 0, this.activeTetromino)) {
// undrawPiece(this.activeTetromino);
// this.x++;
// drawPiece(this.activeTetromino);
// }
// }
// Tetromino.prototype.rotate = function() {
// let nextPattern = this.tetromino[(this.tetrominoN + 1) % 4];
// if(!this.collision(0, 0, nextPattern)) {
// if(this.tetromino.length > 1) {
// undrawPiece(this.activeTetromino);
// this.tetrominoN = (this.tetrominoN + 1) % 4; // take paranthesis off
// this.activeTetromino = this.tetromino[this.tetrominoN];
// drawPiece(this.activeTetromino);
// }
// }
// }
// //create a function to check for collisions
// Tetromino.prototype.collision = function(x, y, piece) {
// for(let r = 0; r < piece.length; r++) {
// for(let c = 0; c < piece.length; c++) {
// //skip index if it is 0
// if(!piece[r][c]) continue;
// //create vars for the future piece position
// let newX = this.x + c + x;
// let newY = this.y + r + y;
// //see if new position collides with border
// if(newX < 0 || newX >= col || newY >= row) return true;
// //see if there's a locked piece on the board
// if(board[newY][newX] !== vacant) return true;
// }
// }
// return false;
// }
// Tetromino.prototype.lock = function() {
// for(let r = 0; r < this.activeTetromino.length; r++) {
// for(let c = 0; c < this.activeTetromino.length; c++) {
// if(!this.activeTetromino[r][c]) continue;
// //if piece reaches the top its gameover
// if(this.y + r < 0) {
// gameover = true;
// alert('Game Over!');
// }
// //lock the piece by updating the board
// board[this.y + r][this.x + c] = this.color;
// }
// }
// }
// let dropStart = Date.now();
// //drop the piece every 1s
// function drop() {
// let now = Date.now();
// let delta = now - dropStart;
// //if delta is greater than 1s drop the piece
// if(delta > 800) {
// p.moveDown();
// dropStart = Date.now();
// }
// requestAnimationFrame(drop);
// }
// drop();
//declare globals
const col = 10;
const row = 20;
const sq = 40;
const vacant = 'black';
const cvs = document.querySelector('#canvas');
const ctx = cvs.getContext('2d');
let gameOver = false;
//create and draw the board
let board = [];
for(let r = 0; r < row; r++) {
board[r] = [];
for(let c = 0; c < col; c++) {
board[r][c] = vacant;
draw(c, r, board[r][c]);
}
}
//create a blueprint function to draw to the board
function draw(x, y, color) {
//set the drawing specifications
ctx.fillStyle = color;
ctx.fillRect(x * sq, y * sq, sq, sq);
ctx.strokeStyle = 'white';
ctx.strokeRect(x * sq, y * sq, sq, sq);
}
//create a blueprint object for the tetrominos
function Piece(tetromino, color) {
//create the properties
this.tetromino = tetromino;
this.color = color;
this.tetrominoN = 0;
this.activeTetromino = this.tetromino[this.tetrominoN];
this.x = 0;
this.y = -1;
if (this.tetromino === pieces[5][0]) this.y = -2;
}
//create an array to hold all of the tetrominos
const pieces = [
[Z, 'red'],
[S, 'limegreen'],
[T, 'yellow'],
[O, 'blue'],
[L, '#b938ff'],
[I, 'cyan'],
[J, 'orange']
]
function randomPiece() {
let r = Math.floor(Math.random()*pieces.length);
return new Piece(pieces[r][0], pieces[r][1]);
}
//grab a piece
let p = randomPiece();
//draw a piece to the board
// drawPiece(p.activeTetromino, p.color);
//create a blueprint function to draw tetrominos to the board
function drawPiece(piece, color) {
for(let r = 0; r < piece.length; r++) {
for(let c = 0; c < piece.length; c++) {
if (!piece[r][c]) continue;
draw(c + p.x, r + p.y, color);
}
}
}
//control the piece
document.addEventListener('keydown', (e) => {
//check user's input
if(e.keyCode === 37) p.moveLeft();
else if(e.keyCode === 38) p.rotate();
else if(e.keyCode === 39) p.moveRight();
else if (e.keyCode === 40) p.moveDown();
});
Piece.prototype.moveDown = function() {
if(!this.collision(0, 1, this.activeTetromino)) {
drawPiece(this.activeTetromino, vacant);
this.y++;
drawPiece(this.activeTetromino, this.color);
} else {
this.lockPiece(this.activeTetromino);
checkForPoints();
p = randomPiece();
}
}
Piece.prototype.moveLeft = function() {
if(!this.collision(-1, 0, this.activeTetromino)) {
drawPiece(this.activeTetromino, vacant);
this.x--;
drawPiece(this.activeTetromino, this.color);
}
}
Piece.prototype.moveRight = function() {
if(!this.collision(1, 0, this.activeTetromino)) {
drawPiece(this.activeTetromino, vacant);
this.x++;
drawPiece(this.activeTetromino, this.color);
}
}
Piece.prototype.rotate = function() {
let nextPattern = this.tetromino[(this.tetrominoN + 1) % 4];
let kick = 0;
if (this.collision(0, 0, nextPattern)) {
if(this.x < col/2) {
if(this.x === -2) {
kick = 2;
} else {
kick = 1; //kick from right
}
}
if(this.x > col/2) {
if(this.tetromino === pieces[5][0]) {
kick = -2;
} else {
kick = -1; //kick from left
}
}
}
if(!this.collision(kick, 0, nextPattern)) {
drawPiece(this.activeTetromino, vacant);
this.x += kick;
this.tetrominoN = (this.tetrominoN + 1) % 4;
this.activeTetromino = this.tetromino[this.tetrominoN];
drawPiece(this.activeTetromino, this.color);
}
}
Piece.prototype.collision = function(x, y, piece) {
for (let r = 0; r < piece.length; r++) {
for(let c = 0; c < piece.length; c++) {
if(!piece[r][c]) continue;
let newX = this.x + c + x;
let newY = this.y + r + y;
if(newX < 0 || newX >= col || newY >= row) return true;
if(board[newY][newX] !== vacant) return true;
}
}
return false;
}
Piece.prototype.lockPiece = function(piece) {
for (let r = 0; r < piece.length; r++) {
for(let c = 0; c < piece.length; c++) {
if(!piece[r][c]) continue;
if(this.y + r === 1) alert('yo');
if(this.y + r <= 0) {
alert('Game Over');
gameOver = true;
break;
}
board[this.y + r][this.x + c] = this.color;
}
}
}
function checkForPoints() {
for(let r = 0; r < row; r++) {
if(board[r].every(squareCheck)) {
alert('yo');
board[r].every(clearSquare);
}
}
function squareCheck(sq) {
if(sq !== vacant) return true;
else return false;
}
function clearSquare(sq) {
sq = vacant;
}
}
//start a time to set as a refrence for the dropstart
let dropStart = Date.now();
//create a blueprint function to drop the piece
function drop() {
//grab the current time
let now = Date.now();
//create a var to hold the difference of the current time
let delta = now - dropStart; //------Why can't these be switched------
if(delta > 800) {
dropStart = Date.now();
p.moveDown();
//------put request animation here------
}
if (!gameOver) requestAnimationFrame(drop);
}
drop();
<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tetris</title>
<link href="https://fonts.googleapis.com/css?family=Orbitron&display=swap" rel="stylesheet">
</head>
<style>
body {
background-color: #595959;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow-y: hidden;
}
canvas {
outline: 1px solid white;
}
.canvas-wrap {
padding-left: 50px;
padding-top: 50px;
position: relative;
}
.num-top, .num-bottom {
position: absolute;
top: -1px;
left: 0;
}
.num-top {
width: 100%;
height: 50px;
}
.num-bottom {
height: 100%;
width: 50px;
}
.nb {
font-family: 'Orbitron';
color: white;
}
.num-wrap-t {
display: flex;
justify-content: space-around;
margin-left: 50px;
width: 400px;
}
.num-wrap-b {
display: flex;
flex-direction: column;
justify-content: space-around;
margin-top: 50px;
height: 800px;
}
.num-wrap-b .nb {
text-align: right;
margin-right: 3px;
}
.num-wrap-t .nb {
position: relative;
top: 31px;
}
</style>
<body>
<div class="canvas-wrap">
<div class="num-top">
<div class="num-wrap-t">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
</div>
</div>
<canvas id="canvas" width="400" height="800"></canvas>
<div class="num-bottom">
<div class="num-wrap-b">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
<div class="nb">10</div>
<div class="nb">11</div>
<div class="nb">12</div>
<div class="nb">13</div>
<div class="nb">14</div>
<div class="nb">15</div>
<div class="nb">16</div>
<div class="nb">17</div>
<div class="nb">18</div>
<div class="nb">19</div>
</div>
</div>
</div>
<script src="tetrominos.js"></script>
<script src="tetris.js"></script>
</body>
</html> -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tetris</title>
<link href="https://fonts.googleapis.com/css?family=Orbitron&display=swap" rel="stylesheet">
</head>
<style>
body, html {
padding: 0;
margin: 0;
}
body {
background-color: #595959;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
canvas {
outline: 1px solid white;
}
.canvas-wrap {
padding-left: 50px;
padding-top: 50px;
position: relative;
}
.num-top, .num-bottom {
position: absolute;
top: -1px;
left: 0;
}
.num-top {
width: 100%;
height: 50px;
}
.num-bottom {
height: 100%;
width: 50px;
}
.nb {
font-family: 'Orbitron';
color: white;
}
.num-wrap-t {
display: flex;
justify-content: space-around;
margin-left: 50px;
width: 400px;
}
.num-wrap-b {
display: flex;
flex-direction: column;
justify-content: space-around;
margin-top: 50px;
height: 800px;
}
.num-wrap-b .nb {
text-align: right;
margin-right: 3px;
}
.num-wrap-t .nb {
position: relative;
top: 31px;
}
</style>
<body>
<div class="canvas-wrap">
<div class="num-top">
<div class="num-wrap-t">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
</div>
</div>
<canvas id="canvas" width="400" height="800"></canvas>
<div class="num-bottom">
<div class="num-wrap-b">
<div class="nb">0</div>
<div class="nb">1</div>
<div class="nb">2</div>
<div class="nb">3</div>
<div class="nb">4</div>
<div class="nb">5</div>
<div class="nb">6</div>
<div class="nb">7</div>
<div class="nb">8</div>
<div class="nb">9</div>
<div class="nb">10</div>
<div class="nb">11</div>
<div class="nb">12</div>
<div class="nb">13</div>
<div class="nb">14</div>
<div class="nb">15</div>
<div class="nb">16</div>
<div class="nb">17</div>
<div class="nb">18</div>
<div class="nb">19</div>
</div>
</div>
</div>
<script src="tetrominos.js"></script>
<script src="tetris.js"></script>
</body>
</html>
JavaScript has call by sharing so if you do sq = that will only affect the local sq variable, not the value in the array. You have to directly assign the new value to the array, e.g. board[r][i] = vacant; ...
Additionally .every is the wrong tool then, use .forEach or for(let i = 0; i < board[r].length; i++) , and then reassign the values.
Or could just create a new array and reassign it:
board[r] = new Array(board[r].length).fill(vacant);
that could also be done with .map.
From documentation:
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
The passed function is a TEST function, I imagine that behind the scenes it creates a copy of your array element and activates the function on it.