Crop image and download it with specific size - javascript

I modified a code to upload an image with specific size and I'm here right now:
imageUploadPrepare();
function imageUploadPrepare() {
var $profileImgDiv = document.getElementById("profile-img-div"),
$profileImg = document.getElementById("profile-img"),
$changePhoto = document.getElementById("change-photo"),
$xPosition = document.getElementById("x-position"),
$yPosition = document.getElementById("y-position"),
$saveImg = document.getElementById("save-img"),
$loader = document.getElementById("loader"),
$cancelImg = document.getElementById("cancel-img"),
$profileImgInput = document
.getElementById("profile-img-input"),
$profileImgConfirm = document
.getElementById("profile-img-confirm"),
$error = document.getElementById("error");
var currentProfileImg = "",
profileImgDivW = getSizes($profileImgDiv).elW,
NewImgNatWidth = 0,
NewImgNatHeight = 0,
NewImgNatRatio = 0,
NewImgWidth = 0,
NewImgHeight = 0,
NewImgRatio = 0,
xCut = 0,
yCut = 0;
makeSquared($profileImgDiv);
$changePhoto.addEventListener("change", function() {
currentProfileImg = $profileImg.src;
showPreview(this, $profileImg);
$loader.style.width = "100%";
$profileImgInput.style.display = "none";
$profileImgConfirm.style.display = "flex";
$error.style.display = "none";
});
$xPosition.addEventListener("input", function() {
$profileImg.style.left = -this.value + "px";
xCut = this.value;
yCut = 0;
});
$yPosition.addEventListener("input", function() {
$profileImg.style.top = -this.value + "px";
yCut = this.value;
xCut = 0;
});
$saveImg.addEventListener("click", function() {
cropImg($profileImg);
resetAll(true);
});
$cancelImg.addEventListener("click", function() {
resetAll(false);
});
window.addEventListener("resize", function() {
makeSquared($profileImgDiv);
profileImgDivW = getSizes($profileImgDiv).elW;
});
function makeSquared(el) {
var elW = el.clientWidth;
el.style.height = (elW * 0.82) + "px";
}
function showPreview(input, el) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
if (input.files && input.files[0]) {
reader.onload = function(e) {
setTimeout(function() {
el.src = e.target.result;
}, 300);
var poll = setInterval(function() {
if (el.naturalWidth && el.src != currentProfileImg) {
clearInterval(poll);
setNewImgSizes(el);
setTimeout(function() {
$loader.style.width = "0%";
$profileImg.style.opacity = "1";
}, 250);
}
}, 100);
};
} else {
return;
}
}
function setNewImgSizes(el) {
if (getNatSizes(el).elR > 1) {
el.style.width = "auto";
el.style.height = "100%";
newImgWidth = getSizes(el).elW;
$xPosition.style.display = "block";
$yPosition.style.display = "none";
$xPosition.max = newImgWidth - profileImgDivW;
} else if (getNatSizes(el).elR < 1) {
el.style.width = "100%";
el.style.height = "auto";
newImgHeight = getSizes(el).elH;
$xPosition.style.display = "none";
$yPosition.style.display = "block";
$yPosition.max = newImgHeight - profileImgDivW;
} else if (getNatSizes(el).elR == 1) {
el.style.width = "100%";
el.style.height = "auto";
$xPosition.style.display = "none";
$yPosition.style.display = "none";
}
}
function getNatSizes(el) {
var elW = el.naturalWidth,
elH = el.naturalHeight,
elR = elW / elH;
return {
elW: elW,
elH: elH,
elR: elR
};
}
function getSizes(el) {
var elW = el.clientWidth,
elH = el.clientHeight,
elR = elW / elH;
return {
elW: elW,
elH: elH,
elR: elR
};
}
function cropImg(el) {
var natClientImgRatio = getNatSizes(el).elW / getSizes(el).elW;
(myCanvas = document.getElementById("croppedPhoto")),
(ctx = myCanvas.getContext("2d"));
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, 400, 487);
ctx.drawImage(
el,
xCut * natClientImgRatio,
yCut * natClientImgRatio,
profileImgDivW * natClientImgRatio,
profileImgDivW * natClientImgRatio,
0,
0,
400,
487
);
var newProfileImgUrl = myCanvas.toDataURL("image/jpeg");
$profileImg.src = newProfileImgUrl;
uploadImage(newProfileImgUrl);
function uploadImage(image) {
const dashboardProfileImage = document.getElementById('profile-img');
dashboardProfileImage.src = image;
downloadImage(image);
dashboardProfileImage.download = "output.png";
async function downloadImage(imageSrc) {
const image = await fetch(imageSrc)
const imageBlog = await image.blob()
const imageURL = URL.createObjectURL(imageBlog)
const link = document.createElement('a')
link.href = imageURL
link.download = 'image file name here'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
}
function resetAll(confirm) {
if (!confirm) {
$profileImg.src = currentProfileImg;
}
$changePhoto.value = "";
$profileImgInput.style.display = "block";
$profileImgConfirm.style.display = "none";
$profileImg.style.left = "0";
$profileImg.style.top = "0";
$profileImg.style.width = "100%";
$profileImg.style.height = "100%";
$xPosition.style.display = "none";
$yPosition.style.display = "none";
$xPosition.value = "0";
$yPosition.value = "0";
xCut = "0";
yCut = "0";
}
function checkMinSizes(el) {
if (getNatSizes(el).elW > 400 && getNatSizes(el).elH > 400) {
return true;
} else {
return false;
}
}
}
/*Profile image*/
.profile-photo-div{
position: relative;
margin: 0 auto 40px auto;
width: 320px;
height: auto;
overflow: hidden;
border-radius: 10px;
-webkit-transition: ease .3s;
-o-transition: ease .3s;
transition: ease .3s;
}
.profile-photo-div .profile-img-div{
display: block;
position: relative;
overflow: hidden;
}
.profile-photo-div #loader{
position: absolute;
top:0;
left: 0;
width: 0%;
height: 100%;
background-color: #00cccf;
z-index:10;
-webkit-transition: .3s;
-o-transition: .3s;
transition: .3s;
}
.profile-photo-div #profile-img{
position: absolute;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.profile-photo-div #change-photo{
display: none;
}
.profile-photo-div .profile-buttons-div{
position: relative;
display: block;
}
.profile-photo-div .button{
position: relative;
display: block;
font-family: helvetica, sans-serif;
font-size: 15px;
padding:15px;
text-align: center;
color: white;
background-color: #8f7cff;
cursor: pointer;
-webkit-transition: .5s;
-o-transition: .5s;
transition: .5s;
overflow: hidden;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.profile-photo-div .button:hover{
letter-spacing: 1px;
}
.profile-photo-div .button:after{
content: '';
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
width: 10px;
height: 10px;
background-color: rgba(255,255,255,0.4);
border-radius: 50%;
opacity: 0;
-webkit-transition: .9s;
-o-transition: .9s;
transition: .9s;
}
.profile-photo-div .button:hover:after{
-webkit-transform: scale(50);
-ms-transform: scale(50);
transform: scale(50);
opacity: 1;
}
.profile-photo-div .button.half{
width: 50%;
}
.profile-photo-div .green{
background-color: #15ae6b;
}
.profile-photo-div .red{
background-color: #ae0000;
}
.profile-photo-div #x-position{
position: absolute;
bottom: 5px;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
display: none;
}
.profile-photo-div #y-position{
position: absolute;
right: -50px;
top: 50%;
-webkit-transform: translateY(-50%) rotate(90deg);
-ms-transform: translateY(-50%) rotate(90deg);
transform: translateY(-50%) rotate(90deg);
display: none;
}
.profile-photo-div canvas{
position: absolute;
top: -2000px;
left: -2000px;
z-index: -1;
}
.profile-photo-div .profile-img-confirm{
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
width: 100%;
}
.profile-photo-div .error{
font-family: Helvetica, sans-serif;
font-size: 13px;
color: red;
text-align:center;
display: none;
}
/*end of profile image*/
<div class="profile-photo-div" id="profile-photo-div">
<div class="profile-img-div" id="profile-img-div" style="height: 150px;">
<div id="loader"></div>
<img id="profile-img" src="/dashboard/img/default-user.png">
<input id="x-position" type="range" name="x-position" value="0" min="0">
<input id="y-position" type="range" name="y-position" value="0" min="0">
</div>
<div class="profile-buttons-div">
<div class="profile-img-input" id="profile-img-input">
<label class="button" id="change-photo-label" for="change-photo">UPLOAD PHOTO</label>
<input id="change-photo" name="change-photo" type="file" style="display: none;" accept="image/*">
</div>
<div class="profile-img-confirm" id="profile-img-confirm" style="display: none;">
<div class="button half green" id="save-img">
<i class="fa fa-check" aria-hidden="true"></i>
</div>
<div class="button half red" id="cancel-img">
<i class="fa fa-remove" aria-hidden="true"></i>
</div>
</div>
</div>
<div class="error" id="error">حداقل سایز مجاز 400×400</div>
<canvas id="croppedPhoto" width="400" height="400"></canvas>
</div>
The issue is so far the image is always cropped with fixed dimensions of 400 * 400 pixels !!
But I want to crop them at 454.138px * 306px and no matter how I modify the numbers I always get that 400* 400 fix size?!
How can fix this?
NOTE: Since Stack overflow snippet code is completely useless in order to test the code please use this Codepen:
https://codepen.io/pixy-dixy/pen/RwZGKBQ

Related

How to show individual ALT tag and URL in responsive popup image gallery

I am pretty new here and also with Javascript but I have tried for quite some time now and can't get my head around how to have individual data in a popup image gallery.
I have tried adding it in multiple ways, and I do not really need a number (1-..) but an individual URL, also an individual description (using the alt tag). So this is the first code that offered it to me and I hope there is some geeks in this community that can give me an easy and quick "fix".
Many thanks in advance!
Here is some code to make you understand better (hopefully):
HTML:
<div class="popup">
<!-- top bar -->
<div class="top-bar">
<p class="image-name">img1.png</p>
<p class="image-description">Just an image</p>
<span class="close-btn"></span>
!-- image -->
<img src="./img/ads/1.png" class="large-image" alt="Just an image">
<!-- image-index -->
<p class="index">01</p>
</div>
<div class="gallery">
<div class="gallery-image">
<img src="./img/ads/1.png" alt="Just an image" class="image">
</div>...
CSS:
.popup {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
width: 80%;
max-width: 100%;
height: 90vh;
max-height: 70%;
border-radius: 20px;
background: rgba(0, 0, 0, 0.75);
display: flex;
justify-content: center;
align-items: center;
z-index: 5;
overflow: hidden;
transition: 1s;
opacity: 0;
}
.popup.active {
transform: translate(-50%, -50%) scale(1);
opacity: 1;
}
.popup.active .close-btn,
.popup.active .image-name,
.popup.active .index,
.popup.active .image-description,
.popup.active .large-image,
.popup.active .arrow-btn {
opacity: 1;
transition: opacity .5s;
transition-delay: 1s;
}
.top-bar {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 50px;
background: #000;
color: #fff;
text-align: center;
line-height: 50px;
font-weight: 300;
}
.image-name {
opacity: 0;
}
.close-btn {
opacity: 0;
position: absolute;
top: 15px;
right: 20px;
width: 20px;
height: 20px;
border-radius: 50%;
background: #f00;
cursor: pointer;
}
JAVASCRIPT:
const popup = document.querySelector('.popup');
const closeBtn = document.querySelector('.close-btn');
const imageName = document.querySelector('.image-name');
const largeImage = document.querySelector('.large-image');
const imageDis = document.querySelector('.image-description');
const imageIndex = document.querySelector('.index');
const leftArrow = document.querySelector('.left-arrow');
const rightArrow = document.querySelector('.right-arrow');
let index = 0; // will track our current image;
images.forEach((item, i) => {
item.addEventListener('click', () => {
updateImage(i);
popup.classList.toggle('active');
});
});
const updateImage = i => {
let path = `./img/ads/${i + 1}.png`;
largeImage.src = path;
imageName.innerHTML = path;
imageIndex.innerHTML = `0${i + 1}`;
index = i;
};
closeBtn.addEventListener('click', () => {
popup.classList.toggle('active');
});
leftArrow.addEventListener('click', () => {
if (index > 0) {
updateImage(index - 1);
}
});
rightArrow.addEventListener('click', () => {
if (index < images.length - 1) { updateImage(index + 1); } });```

Touchscreen Auto Image Slider is showing white space

I am trying to make a touchscreen auto image slider for a landing page and it's somewhat working as it should. However, the image slider sometimes shows white space after a certain amount of scrolls.
Here's the code:
const slides = document.getElementById("slides");
const allSlides = document.querySelectorAll(".slide");
const slidesLength = allSlides.length;
const slideWidth = allSlides[0].offsetWidth;
let index = 0;
let posX1;
let posX2;
let initialPosition;
let finalPosition;
var myTimer;
let canISlide = true;
const prev = document.getElementById("prev");
const next = document.getElementById("next");
const firstSlide = allSlides[0];
const lastSlide = allSlides[allSlides.length - 1];
const cloneFirstSlide = firstSlide.cloneNode(true);
const cloneLastSlide = lastSlide.cloneNode(true);
slides.appendChild(cloneFirstSlide);
slides.insertBefore(cloneLastSlide, firstSlide);
next.addEventListener("click", () => switchSlide("next"));
prev.addEventListener("click", () => switchSlide("prev"));
slides.addEventListener("transitionend", checkIndex);
slides.addEventListener("mouseown", dragStart);
slides.addEventListener("touchstart", dragStart);
slides.addEventListener("touchmove", dragMove);
slides.addEventListener("touchend", dragEnd);
function dragStart(e) {
e.preventDefault();
initialPosition = slides.offsetLeft;
if (e.type == "touchstart") {
posX1 = e.touches[0].clientX;
} else {
posX1 = e.clientX;
document.onmouseup = dragEnd;
document.onmousemove = dragMove;
}
}
function dragMove(e) {
if (e.type == "touchmove") {
posX2 = posX1 - e.touches[0].clientX;
posX1 = e.touches[0].clientX;
} else {
posX2 = posX1 - e.clientX;
posX1 = e.clientX;
}
slides.style.left = `${slides.offsetLeft - posX2}px`;
}
function dragEnd() {
/*
three possibilities:
1. next slide
2. prev slide
3. stay still
*/
finalPosition = slides.offsetLeft;
if (finalPosition - initialPosition < -496) {
switchSlide("next", "dragging");
} else if (finalPosition - initialPosition > 496) {
switchSlide("prev", "dragging");
} else {
slides.style.left = `${initialPosition}px`;
}
document.onmouseup = null;
document.onmousemove = null;
}
function switchSlide(arg, arg2) {
slides.classList.add("transition");
if (canISlide) {
if (!arg2) {
initialPosition = slides.offsetLeft;
}
if (arg == "next") {
slides.style.left = `${initialPosition - slideWidth}px`;
index++;
} else {
slides.style.left = `${initialPosition + slideWidth}px`;
index--;
}
}
canISlide = false;
}
function checkIndex() {
slides.classList.remove("transition");
if (index == -1) {
slides.style.left = `-${slidesLength * slideWidth}px`;
index = slidesLength - 1;
}
if (index == slidesLength) {
slides.style.left = `-${1 * slideWidth}px`;
index = 0;
}
canISlide = true;
}
* {
box-sizing: border-box;
}
.container body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
max-height: 100vh;
}
img {
width: 100%;
height: 100%;
}
.slider {
overflow: hidden;
position: relative;
width: 1080px;
height: 500px;
margin: auto;
}
.slides {
width: 10000px;
display: flex;
position: absolute;
top: 0;
left: -1080px;
cursor: pointer;
}
.slides.transition {
transition: all 0.3s ease-in-out;
}
.slide {
width: 1080px;
height: 500px;
animation: slide 16s infinite;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
color: #f3f3f3;
font-size: 4rem;
}
.next {
right: 2rem;
}
.prev {
left: 2rem;
}
.next:hover, .prev:hover {
transition: 0.2s ease-in-out;
}
.active {
background-color: #ffffff;
-webkit-transition: all 0.4s ease-in-out;
-moz-transition: all 0.4s ease-in-out;
-ms-transition: all 0.4s ease-in-out;
-o-transition: all 0.4s ease-in-out;
transition: all 0.4s ease-in-out;
}
#keyframes slide{
0%{
transform: translateX(0);
}
25%{
transform: translateX(0);
}
30%{
transform: translateX(-100%);
}
50%{
transform: translateX(-100%);
}
55%{
transform: translateX(-200%);
}
75%{
transform: translateX(-200%);
}
80%{
transform: translateX(-300%);
}
100%{
transform: translateX(-300%);
}
}
<div class="container">
<div class="slider">
<div class="slides" id="slides">
<span class="slide">
<a href="#">
<img loading="lazy" src="img.png" alt="" width="100%"></a>
</span>
<span class="slide">
<a href="#">
<img loading="lazy" src="img2.png"></a>
</span>
<span class="slide">
<a href="#">
<img loading="lazy" src="img3-png" width="100%"></a>
</span>
</div>
<a href="#" id="prev" class="prev">❮
<i class="fas fa-caret-left"></i>
</a>
<a href="#" id="next" class="next">❯
<i class="fas fa-caret-right"></i>
</a>
</div>
Of course, I can also just leave out the automatic scrolling, but that isn't quite the goal. The goal is to have the image slider move automatically with a touch function, while working smoothly.
Thank you!

In my code there is an event listener for running every animation iteration but it keep getting the error reading properties of null. Can I fix it?

I am trying to make a traffic game using javascript though every time I try to use this line of code:
carAnimation.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 5);
left = random * 90 + 15;
carAnimation.style.left = left + "px";
counter++;
console.log(counter)
});
I am getting the error
Uncaught TypeError: Cannot read properties of null (reading
'addEventListener')
at HTMLButtonElement. (script.js:40:18)
but I can't seem to find the error in the line. Also, I am trying to run the same code for 3 different elements but it just doesn't seem to work either.
Here is the rest of the code if needed to solve this mystery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="game">
<div class="car"></div>
<div class="npcCar"></div>
<div class="npcCar npcCar2"></div>
<div class="npcCar npcCar3"></div>
</div>
<button class="start">Start!</button>
<div class="controlContainer">
<button class="btn pause"></button>
<button class="btn play"></button>
<button class="btn restart"></button>
<button class="btn help"></button>
</div>
<div class="helpModal hidd">
<div class="modal hidden">
<button class="close-modal">×</button>
<h1>Help</h1>
<p>
HOW TO PLAY:
Use WASD to the arrow keys to move the red car around.
You need to avoid hitting the blue cars.
When you hit a car you will automatically lose
The longer you last the more points you get
Good luck racer!
</p>
</div>
</div>
<style>
#import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
min-height: 100vh;
width: 100%;
background-color: rgb(69, 169, 240);
font-family: 'Oswald', sans-serif;
}
.game{
position: absolute;
left: calc(50% - 450px/2);;
height: 600px;
width: 450px;
border: 3px solid black;
border-radius: 5%;
background: url('road.png');
overflow: hidden;
}
.start{
position: absolute;
height: 30px;
width: 150px;
background-color: rgb(1, 255, 1);
border: 3px solid black;
border-radius: 5%;
font-size: 15px;
font-weight: bold;
top: 600px;
left : calc(50% - 150px/2);
transition: 0.5s;
}
.start:hover{
background: red;
}
.controlContainer{
padding: 5px;
width: 120px;
height: 120px;
border: 3px solid black;
border-radius: 5%;
background-color: lawngreen;
}
.btn{
height: 50px;
width: 50px;
border: 2px solid black;
border-radius: 50%;
}
.play{
background-image: url('play.png');
}
.pause{
background-image: url('pause.png');
}
.help{
background-image: url('help.png');
}
.restart{
background-image: url('restart.png');
}
.animate{
animation: road linear infinite 0.5s;
}
.hidden{
display: none;
}
#keyframes road{
0%{
background-position-y: 0px;
}
100%{
background-position-y: 600px;
}
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 45%;
background-color: white;
padding: 6rem;
border-radius: 5px;
box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3);
z-index: 100000000;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 5rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
.car{
position: relative;;
height: 120px;
width: 60px;
border-radius: 5%;
top: 435px;
background: url('Player (1).png');
transform: rotate(180deg);
z-index: 100000;
}
.npcCar{
width: 60px;
height: 120px;
background: url('obsacle.png');
position: relative;
left: 15px;
top: -300px;
}
.npcCar2{
top: -420px;
left: 195px;;
}
.npcCar3{
top: -540px;
left: 375px
}
.carAnimate{
animation: vroom 0.8s linear infinite;
}
.carAnimate2{
animation: vroom 0.8s linear infinite;
}
.carAnimate3{
animation: vroom 0.8s linear infinite;
}
#keyframes vroom{
0%{
top: -120px;
}
100%{
top: 600px;
}
}
</style>
<script>
'use strict'
const startBtn = document.querySelector('.start')
const pauseBtn = document.querySelector('.pause')
const playBtn = document.querySelector('.play')
const restartBtn = document.querySelector('.restart')
const helpBtn = document.querySelector('.help')
const modal = document.querySelector('.modal');
const closeModal = document.querySelector('.close-modal');
const game = document.querySelector('.game');
const player = document.querySelector('.car');
const npcPlayer = document.querySelector('.npcCar');
const npcPlayer2 = document.querySelector('.npcCar2');
const npcPlayer3 = document.querySelector('.npcCar3');
const carAnimation = document.querySelector('.carAnimate');
const carAnimation2 = document.querySelector('.carAnimate2');
const carAnimation3 = document.querySelector('.carAnimate3');
let click = 0;
let interval;
let both = 0;
let counter = 0;
//onLoad
window.addEventListener("load", () => {
player.style.position = "relative";
player.style.left = '195px';
player.style.top = '485px';
});
// Start the Game
startBtn.addEventListener('click', function(){
console.log('button clicked');
game.classList.add('animate');
click+=2;
npcPlayer.classList.add('carAnimate')
npcPlayer2.classList.add('carAnimate2')
npcPlayer3.classList.add('carAnimate3')
carAnimation.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 5);
left = random * 90 + 15;
carAnimation.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation2.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation2.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation3.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation3.style.left = left + "px";
counter++;
});
});
//Pausing the Game
pauseBtn.addEventListener('click', function(){
console.log('button clicked');
if(click>1){
game.classList.remove('animate');
click--
}
console.log(click)
});
//Resuming the Game
playBtn.addEventListener('click', function(){
console.log('button clicked');
if(click===1){
game.classList.add('animate');
click++;
console.log(click);
}
});
//Opening the Help Model
helpBtn.addEventListener('click', function(){
console.log('modal clicked')
modal.classList.remove('hidden')
});
//closing the help modal
closeModal.addEventListener('click', function(){
console.log('button clicked')
modal.classList.add('hidden')
});
//Moving Functions
function moveLeft() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
var transform = parseInt(window.getComputedStyle(player).getPropertyValue("transform"));
if (left > -0) {
player.style.left = left - 2 + "px";
player.style.transform = 'rotate(-' + 215 + 'deg)'
}
}
function moveRight() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
if (left < 385) {
player.style.left = left + 2 + "px";
player.style.transform = 'rotate(' + 215 + 'deg)'
}
}
function moveUp() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top > 0) {
player.style.top = top - 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
function moveDown() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top < 490) {
player.style.top = top + 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
//Make the pLayer move
document.addEventListener("keydown", (event) => {
if (both == 0) {
both++;
if (event.key === "ArrowLeft") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "ArrowRight") {
interval = setInterval(moveRight, 1);
}
if (event.key === "ArrowUp") {
interval = setInterval(moveUp, 1);
}
if (event.key === "ArrowDown") {
interval = setInterval(moveDown, 1);
}
if (event.key === "a") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "d") {
interval = setInterval(moveRight, 1);
}
if (event.key === "w") {
interval = setInterval(moveUp, 1);
}
if (event.key === "s") {
interval = setInterval(moveDown, 1);
}
}
});
document.addEventListener("keyup", (event) => {
clearInterval(interval);
both = 0;
player.style.transform = 'rotate(' + 180 + 'deg)'
});
</script>
</body>
</html>
Thanks!
Try wrapping all of your code inside the below document-content-ready function
document.addEventListener("DOMContentLoaded", () => {
//your entire js code here
});
make sure your code will run after the document's load is complete. you can do that by checking readyState like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="game">
<div class="car"></div>
<div class="npcCar"></div>
<div class="npcCar npcCar2"></div>
<div class="npcCar npcCar3"></div>
</div>
<button class="start">Start!</button>
<div class="controlContainer">
<button class="btn pause"></button>
<button class="btn play"></button>
<button class="btn restart"></button>
<button class="btn help"></button>
</div>
<div class="helpModal hidd">
<div class="modal hidden">
<button class="close-modal">×</button>
<h1>Help</h1>
<p>
HOW TO PLAY:
Use WASD to the arrow keys to move the red car around.
You need to avoid hitting the blue cars.
When you hit a car you will automatically lose
The longer you last the more points you get
Good luck racer!
</p>
</div>
</div>
<style>
#import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
min-height: 100vh;
width: 100%;
background-color: rgb(69, 169, 240);
font-family: 'Oswald', sans-serif;
}
.game{
position: absolute;
left: calc(50% - 450px/2);;
height: 600px;
width: 450px;
border: 3px solid black;
border-radius: 5%;
background: url('road.png');
overflow: hidden;
}
.start{
position: absolute;
height: 30px;
width: 150px;
background-color: rgb(1, 255, 1);
border: 3px solid black;
border-radius: 5%;
font-size: 15px;
font-weight: bold;
top: 600px;
left : calc(50% - 150px/2);
transition: 0.5s;
}
.start:hover{
background: red;
}
.controlContainer{
padding: 5px;
width: 120px;
height: 120px;
border: 3px solid black;
border-radius: 5%;
background-color: lawngreen;
}
.btn{
height: 50px;
width: 50px;
border: 2px solid black;
border-radius: 50%;
}
.play{
background-image: url('play.png');
}
.pause{
background-image: url('pause.png');
}
.help{
background-image: url('help.png');
}
.restart{
background-image: url('restart.png');
}
.animate{
animation: road linear infinite 0.5s;
}
.hidden{
display: none;
}
#keyframes road{
0%{
background-position-y: 0px;
}
100%{
background-position-y: 600px;
}
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 45%;
background-color: white;
padding: 6rem;
border-radius: 5px;
box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3);
z-index: 100000000;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 5rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
.car{
position: relative;;
height: 120px;
width: 60px;
border-radius: 5%;
top: 435px;
background: url('Player (1).png');
transform: rotate(180deg);
z-index: 100000;
}
.npcCar{
width: 60px;
height: 120px;
background: url('obsacle.png');
position: relative;
left: 15px;
top: -300px;
}
.npcCar2{
top: -420px;
left: 195px;;
}
.npcCar3{
top: -540px;
left: 375px
}
.carAnimate{
animation: vroom 0.8s linear infinite;
}
.carAnimate2{
animation: vroom 0.8s linear infinite;
}
.carAnimate3{
animation: vroom 0.8s linear infinite;
}
#keyframes vroom{
0%{
top: -120px;
}
100%{
top: 600px;
}
}
</style>
<script>
'use strict'
if (document.readyState === "complete") {
const startBtn = document.querySelector('.start')
const pauseBtn = document.querySelector('.pause')
const playBtn = document.querySelector('.play')
const restartBtn = document.querySelector('.restart')
const helpBtn = document.querySelector('.help')
const modal = document.querySelector('.modal');
const closeModal = document.querySelector('.close-modal');
const game = document.querySelector('.game');
const player = document.querySelector('.car');
const npcPlayer = document.querySelector('.npcCar');
const npcPlayer2 = document.querySelector('.npcCar2');
const npcPlayer3 = document.querySelector('.npcCar3');
const carAnimation = document.querySelector('.carAnimate');
const carAnimation2 = document.querySelector('.carAnimate2');
const carAnimation3 = document.querySelector('.carAnimate3');
let click = 0;
let interval;
let both = 0;
let counter = 0;
//onLoad
window.addEventListener("load", () => {
player.style.position = "relative";
player.style.left = '195px';
player.style.top = '485px';
});
// Start the Game
startBtn.addEventListener('click', function(){
console.log('button clicked');
game.classList.add('animate');
click+=2;
npcPlayer.classList.add('carAnimate')
npcPlayer2.classList.add('carAnimate2')
npcPlayer3.classList.add('carAnimate3')
carAnimation.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 5);
left = random * 90 + 15;
carAnimation.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation2.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation2.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation3.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation3.style.left = left + "px";
counter++;
});
});
//Pausing the Game
pauseBtn.addEventListener('click', function(){
console.log('button clicked');
if(click>1){
game.classList.remove('animate');
click--
}
console.log(click)
});
//Resuming the Game
playBtn.addEventListener('click', function(){
console.log('button clicked');
if(click===1){
game.classList.add('animate');
click++;
console.log(click);
}
});
//Opening the Help Model
helpBtn.addEventListener('click', function(){
console.log('modal clicked')
modal.classList.remove('hidden')
});
//closing the help modal
closeModal.addEventListener('click', function(){
console.log('button clicked')
modal.classList.add('hidden')
});
//Moving Functions
function moveLeft() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
var transform = parseInt(window.getComputedStyle(player).getPropertyValue("transform"));
if (left > -0) {
player.style.left = left - 2 + "px";
player.style.transform = 'rotate(-' + 215 + 'deg)'
}
}
function moveRight() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
if (left < 385) {
player.style.left = left + 2 + "px";
player.style.transform = 'rotate(' + 215 + 'deg)'
}
}
function moveUp() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top > 0) {
player.style.top = top - 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
function moveDown() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top < 490) {
player.style.top = top + 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
//Make the pLayer move
document.addEventListener("keydown", (event) => {
if (both == 0) {
both++;
if (event.key === "ArrowLeft") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "ArrowRight") {
interval = setInterval(moveRight, 1);
}
if (event.key === "ArrowUp") {
interval = setInterval(moveUp, 1);
}
if (event.key === "ArrowDown") {
interval = setInterval(moveDown, 1);
}
if (event.key === "a") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "d") {
interval = setInterval(moveRight, 1);
}
if (event.key === "w") {
interval = setInterval(moveUp, 1);
}
if (event.key === "s") {
interval = setInterval(moveDown, 1);
}
}
});
document.addEventListener("keyup", (event) => {
clearInterval(interval);
both = 0;
player.style.transform = 'rotate(' + 180 + 'deg)'
});
}
</script>

CSS 360 rotating progress radial using JS

var ele = document.getElementById("filler");
var deg = 0;
var myInterval = setInterval(function() {
deg = deg + 10;
if (deg > 360) {
clearInterval(myInterval);
}
ele.style.transform = `rotate(${deg}deg)`;
}, 500);
.filler-wrapper {
height: 100px;
width: 100px;
position: relative;
border-radius: 50%;
overflow: hidden;
background: linear-gradient(to left, red 50%, green 50%);
}
.filler {
border-radius: 0 100% 100% 0 / 50%;
display: block;
height: 100%;
margin-left: 50%;
transform-origin: left;
background: green;
transform: rotate(0deg)
}
<div class="filler-wrapper">
<div id="filler" class="filler"></div>
</div>
I have created this radial progress but this works for only 180. How can I make it to rotate 360 deg.
Here is an idea based on this previous answer where you can do this with only background:
var ele = document.getElementById("box");
var deg = -90;
var s = 1;
var myInterval = setInterval(function() {
if(deg >= 90 && s) {
ele.style.setProperty("--s", --s);
deg = -90;
}
deg = deg + 10;
ele.style.setProperty("--v", deg+'deg');
if(deg >= 90 && !s) {
clearInterval(myInterval);
}
}, 500);
#box {
width:100px;
height:100px;
border-radius:50%;
background:
linear-gradient(var(--v), green 50%,transparent 0) center/calc(var(--s)*100%),
linear-gradient(var(--v), red 50%, transparent 0) center/calc(100% - var(--s)*100%),
linear-gradient(to right, green 50%,red 0);
}
<div id="box" style="--v:-90eg;--s:1"></div>
<!-- first cycle : from -90deg to 90deg with s=1 -->
<!-- second cycle : from -90deg to 90deg with s=0 -->
Shortly this will be something trivial with conic-gradient():
var ele = document.getElementById("box");
var deg = 0;
var myInterval = setInterval(function() {
deg = deg + 10;
ele.style.setProperty("--v", deg+'deg');
if(deg >= 360 ) {
clearInterval(myInterval);
}
}, 500);
#box {
width:100px;
height:100px;
border-radius:50%;
background:
conic-gradient(red var(--v,0deg),green var(--v,0deg),green 360deg);
}
<div id="box" ></div>
The above should work only on Chrome
For JS
isCompleted = false;
progressCount = 10;
function updateProgress() {
progressCount = progressCount + 10;
const _count = progressCount * 1.8;
console.log(_count)
if (_count > 180) {
isCompleted = true;
}
if (this.isCompleted) {
return;
}
_rotateSpinner(_count);
}
var elCircleFullFill = document.getElementById("circleFullFill");
var elCircleHalfFill = document.getElementById("circleHalfFill");
var elCircleMaskFull = document.getElementById("circleMaskFull");
var elCircleFillFix = document.getElementById("circleFillFix");
function _rotateSpinner(__progressCount) {
const fillRotation = __progressCount;
const fixRotation = __progressCount * 2;
elCircleFullFill.style = `transform:rotate(${fillRotation}deg)`;
elCircleHalfFill.style = `transform:rotate(${fillRotation}deg)`;
elCircleMaskFull.style = `transform:rotate(${fillRotation}deg)`;
elCircleFillFix.style = `transform:rotate(${fixRotation}deg)`;
}
SCSS
.progress-radial {
width: 50px;
height: 50px;
background-color: #fff;
border-radius: 50%;
.circle {
.circle-mask,
.circle-fill {
width: 50px;
height: 50px;
position: absolute;
border-radius: 50%;
transition: -webkit-transform 1s;
transition: -ms-transform 1s;
transition: transform 1s;
-webkit-backface-visibility: hidden;
}
.circle-mask {
clip: rect(0px, 50px, 50px, 50px/2);
.circle-fill {
clip: rect(0px, 50px/2, 50px, 0px);
background-color: #0096FF;
}
}
}
}
HTML
<div class="progress-radial">
<div class="circle">
<div class="circle-mask" id="circleMaskFull">
<div class="circle-fill" id="circleFullFill"></div>
</div>
<div class="circle-mask">
<div class="circle-fill" id="circleHalfFill"></div>
<div class="circle-fill" id="circleFillFix"></div>
</div>
</div>
</div>
<button onclick="updateProgress()">Update Spinner</button>

Pure JS + CSS Slideshow with z-Index: Glitch on last Slide

I try to build a Slideshow in JS + CSS and it works pretty well except one visual glitch. The Transition to the last slides seems somehow broken.
But I couldn't figure out what the problem is. If I comment out the "offset" transition on the last slide, the error doesn't occure.
This is the codeine I am talking about: https://codepen.io/marianbreitmeyer/pen/paeYgZ
The Block of code I mentioned is this one:
const showNext = function() {
clicked = true;
for (i = 0; i <= slides.length-1; i++) {
if( parseInt(slides[i].style.zIndex) === slides.length) {
console.log(slides[i].innerHTML);
triggerAnimation(slides[i], 'offcanvas');
} else if (parseInt(slides[i].style.zIndex) === slides.length-1) {
//the line below triggers the problem
triggerAnimation(slides[i], 'offset');
}
}
};
Maybe someone with more experience could help me :)
Your code might be more simple:
const btn = document.getElementsByClassName('arrow')[0];
const slides = document.getElementsByClassName('slide');
slides[slides.length - 1].classList.add('offset', 'next');
btn.addEventListener("click", function(e) {
var o, n;
for (var i = 0; i < slides.length; i++) {
if (slides[i].classList.contains('offset')) {
slides[i].classList.remove('offset', 'next')
slides[i].classList.add('offcanvas');
o = (slides[i - 1] || slides[slides.length - 1]);
n = (slides[i - 2] || slides[slides.length + i - 2]);
}
if (slides[i].offsetLeft < -slides[i].offsetWidth) {
slides[i].classList.remove('offcanvas', 'next');
}
}
o.classList.add('offset');
n.classList.add('next');
}, false);
.container {
width: 100%;
height: 100vh;
background: brown;
position: relative;
}
body {
text-align: center;
font-size: 2rem;
}
.slide {
position: absolute;
top: 0;
left: 90%;
width: 100%;
height: 100%;
}
.slide:nth-child(1) {
background: pink;
}
.slide:nth-child(2) {
background: blue;
}
.slide:nth-child(3) {
background: green;
}
.slide:nth-child(4) {
background: grey;
}
.slide:nth-child(5) {
background: yellow;
}
.slide.next {z-index:1}
.slide.offset {
left: -10%;
z-index: 2;
transition: left .65s ease-in-out;
}
.slide.offcanvas {
left: -110%;
z-index: 2;
transition: left .65s ease-in-out;
}
.arrow {
position: absolute;
right: 5%;
top: 25px;
z-index: 9;
height: 50px;
width: 50px;
cursor: pointer;
}
.arrow:hover path {
transform: translate(16px, 0px);
}
path {
position: absolute;
top: 0;
left: 0;
transition: all .2s ease-in-out;
}
<div class="container">
<div class="slide">1 = pink</div>
<div class="slide">2 = blue</div>
<div class="slide">3 = green</div>
<div class="slide">4 = grey</div>
<div class="slide">5 = yellow</div>
<svg xmlns="http://www.w3.org/2000/svg" class="arrow"><path d="M19.443 5.17L30.138 15.5H-.095v1h30.233L19.443 26.829l.696.719L32.095 16 20.139 4.451z"/></svg>
</div>

Categories

Resources