Ping Pong in Java Script - javascript

I'm trying to figure out why Positions are returned NaN in browser.
this game being rendered in loop and updated as soon as monitor ready to, that's defined in update() function an runs infinite.
reset() function is a part of updating so it will randomly generate headings, also there is a while which corresponds to filtering little and boring movements.
Positions are consist of
A direction which is an Array having x,y times..
A Velocity which is constant during the whole game..
Differ value constitute of time delta indicates how much
milliseconds passed from last rendered frame to the new one
I appreciate your help.
//br.js
const ausgebur_Velocity = .002
class Ball {
constructor(ballElement) {
this.ballElement = ballElement
this.reset()
}
get x() {
return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("--x"))
}
set x(value) {
this.ballElement.style.setProperty("--x", value)
}
get y() {
return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("--y"))
}
set y(value) {
this.ballElement.style.setProperty("--y", value)
}
reset() {
this.x = 50;
this.y = 50;
this.direction = { x: 50, y: 25 }
while (Math.abs(this.direction.x) <= .2 || Math.abs(this.direction.x >= .9)) {
const heading = randomNumberBet(0, 2 * Math.PI)
this.direction = { x: Math.cos(heading), y: Math.sin(heading) }
}
this.velocity = ausgebur_Velocity
}
update(differ) {
this.x += this.direction.x * this.velocity * differ;
this.y += this.direction.y * this.velocity * differ;
console.log(this.x)
console.log(this.y)
}
}
function randomNumberBet(min, max) {
return Math.random() * (max - min) + min
}
// Main Script Below
const ball = new Ball(document.getElementById('ball'))
let lastTime
function update(time) {
if (lastTime != null) {
const differ = time - lastTime
ball.update()
}
lastTime = time
window.requestAnimationFrame(update)
}
window.requestAnimationFrame(update)
//style.css
*,
*::after,
*::before {
box-sizing: border-box;
}
:root {
--hue: 200;
--saturation: 50%;
--foreground: hsl(var(--hue), var(--saturation), 75%);
--background: hsl(var(--hue), var(--saturation), 25%);
}
body {
overflow: hidden;
margin: 0;
background-color: var(--background)
}
.control {
--position: 50;
position: absolute;
background-color: var(--foreground);
top: calc(var(--position)*1vh);
transform: translateY(-50%);
width: 1vh;
height: 10vh;
}
#player_control {
left: 1vw;
}
#pc_control {
right: 1vw;
}
#ball {
--x: 50;
--y: 50;
position: absolute;
background-color: var(--foreground);
left: calc(var(--x)*1vh);
top: calc(var(--y)*1vh);
transform: translate(-50%, -50%);
width: 3vh;
height: 3vh;
border-radius: 50%;
}
.score {
display: flex;
justify-content: center;
font-weight: bold;
font-size: 7vh;
color: var(--foreground);
}
.score>* {
flex-grow: 1;
flex-basis: 0%;
padding: 0 2vh;
margin: 1vh 0;
opacity: .5;
}
.score>:first-child {
text-align: right;
border-right: .5vh solid var(--foreground);
}
//ping.html
<!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">
<link rel="stylesheet" href="/style.css">
<script src="/br.js" type="module"></script>
<title>PING</title>
</head>
<body>
<div class="score">
<div class="player_score">0</div>
<div class="pc_score">0</div>
</div>
<div id="ball"></div>
<div class="control" id="player_control"></div>
<div class="control" id="pc_control"></div>
</body>
</html>

It seems the the problem is that get the coordonates from --x and --y css properties, which are not defined here.
Using top and left works slightly better but I think you'ill have to improve your algorithms.
const ausgebur_Velocity = .002
class Ball {
constructor(ballElement) {
this.ballElement = ballElement
this.reset()
}
get x() {
return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("left"))
}
set x(value) {
this.ballElement.style.setProperty("left", "" + value + "px")
}
get y() {
return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("top"))
}
set y(value) {
this.ballElement.style.setProperty("top", "" + value + "px")
}
reset() {
this.x = 50;
this.y = 50;
this.direction = {
x: 50,
y: 25
}
while (Math.abs(this.direction.x) <= .2 || Math.abs(this.direction.x >= .9)) {
const heading = randomNumberBet(0, 2 * Math.PI)
this.direction = {
x: Math.cos(heading),
y: Math.sin(heading)
}
}
this.velocity = ausgebur_Velocity
}
update(differ) {
this.x += this.direction.x * this.velocity * differ;
this.y += this.direction.y * this.velocity * differ;
console.log("x", this.x)
console.log("y", this.y)
}
}
function randomNumberBet(min, max) {
return Math.random() * (max - min) + min
}
// Main Script Below
const ball = new Ball(document.getElementById('ball'))
let lastTime
function update(time) {
if (lastTime != null) {
const differ = time - lastTime
ball.update(differ)
}
lastTime = time
window.requestAnimationFrame(update)
}
window.requestAnimationFrame(update)
*,
*::after,
*::before {
box-sizing: border-box;
}
:root {
--hue: 200;
--saturation: 50%;
--foreground: hsl(var(--hue), var(--saturation), 75%);
--background: hsl(var(--hue), var(--saturation), 25%);
}
body {
overflow: hidden;
margin: 0;
background-color: var(--background)
}
.control {
--position: 50;
position: absolute;
background-color: var(--foreground);
top: calc(var(--position)*1vh);
transform: translateY(-50%);
width: 1vh;
height: 10vh;
}
#player_control {
left: 1vw;
}
#pc_control {
right: 1vw;
}
#ball {
--x: 50;
--y: 50;
position: absolute;
background-color: var(--foreground);
left: calc(var(--x)*1vh);
top: calc(var(--y)*1vh);
transform: translate(-50%, -50%);
width: 3vh;
height: 3vh;
border-radius: 50%;
}
.score {
display: flex;
justify-content: center;
font-weight: bold;
font-size: 7vh;
color: var(--foreground);
}
.score>* {
flex-grow: 1;
flex-basis: 0%;
padding: 0 2vh;
margin: 1vh 0;
opacity: .5;
}
.score>:first-child {
text-align: right;
border-right: .5vh solid var(--foreground);
}
<!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">
<link rel="stylesheet" href="/style.css">
<script src="/br.js" type="module"></script>
<title>PING</title>
</head>
<body>
<div class="score">
<div class="player_score">0</div>
<div class="pc_score">0</div>
</div>
<div id="ball"></div>
<div class="control" id="player_control"></div>
<div class="control" id="pc_control"></div>
</body>
</html>

Related

How do I move the position of canvas using either css or javascript?

this is my first question here. I am fairly new to html, css, and javascript.
What I wanted to achieve was similar to this mockup i've created:
my website mockup
I've tried to replace the rectangle on the left side with javascript code to achieve a similar effect. The javascript code was taken from this codepen:
https://codepen.io/vaaghu/pen/abmYGYz
I've nudged the canvas a bit to the right, but if i extend the canvas width and height, the canvas does extend, but the circle animations don't. How do I extend this animation?
var canvas = document.querySelector("canvas")
canvas.width = 800;
canvas.height = 1600;
var c = canvas.getContext("2d");
var mouse = {x:innerWidth/2,y:innerHeight/2}
window.addEventListener("mousemove",(event)=>{
mouse.x = event.x;
mouse.y = event.y;
})
window.addEventListener("resize",()=>{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
int();
})
function Circle(x, y,dx,dy,radius,color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color
var maxRadius = 30;
this.draw = function() {
c.beginPath();
c.arc(this.x,this.y,this.radius,0,Math.PI * 2,false);
c.fillStyle = color
c.fill();
}
this.update = function(){
if(this.x+this.radius > innerWidth || this.x-this.radius < 0) {
this.dx = -this.dx;
}
if(this.y+this.radius > innerHeight || this.y -this.radius < 0 ) {
this.dy = -this.dy;
}
if( mouse.x - this.x > -50 && mouse.x - this.x < 50 && mouse.y - this.y >-50 && mouse.y - this.y < 50) {
if (this.radius < maxRadius) {
this.radius += 1
}
} else {
if (this.radius > radius) {
this.radius -= 1
}
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
var colorArray = ["#F5871A","#81968F","#DFAA2F","#D76034","#F5411D"];
var circleArray = []
function int() {
circleArray = []
for (let i = 0; i < 700; i++) {
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
var radius = Math.random() * 5 + 2;
var dx = Math.random() - 0.5;
var dy = Math.random() - 0.5;
var color = colorArray[Math.floor(Math.random()*4)]
circleArray.push(new Circle(x,y,dx,dy,radius,color))
}
}
int()
function animate() {
requestAnimationFrame(animate);
c.clearRect(0,0,innerWidth,innerHeight)
for (let i = 0; i < circleArray.length; i++) {
circleArray[i].update()
}
}
animate();
.mediaViewInfo {
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial, Manrope;
}
:root {
--web-view-ids: Homepage;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: none;
}
#Homepage {
position: absolute;
width: 100%;
height:450%;
font-family: arial, Manrope;
background-color: rgba(255,255,255,1);
overflow: hidden;
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial;
}
canvas {
background: #FFFF05;
background-image: linear-gradient(to bottom, #81968F99, #FFE636CC, #FF000066);
margin: 50% 0% 0% 8%;
padding: 0vh 0vh 0vh 0vh;
z-index:-1;
width:auto;
}
#Wave_Vid {
position: absolute;
left: -19px;
top: -1920px;
width: 100vh;
height: 100vh;
overflow: hidden;
}
.Wave_container {
overflow: visible;
}
#MIDDLEcontainer {
position:absolute;
top: 24%;
left:59%;
}
#MIDDLE {
overflow: visible;
}
#Good_ideas_can_take_time {
line-height: 0.8;
width: 100%;
text-align: left;
padding-right: 10%;
font-family: Manrope, arial;
font-style: normal;
font-weight: bold;
font-size: 15vh;
color: rgba(129,150,143,1);
margin-bottom: 30px;
}
#And_execution_takes_even_more {
width: 100%;
line-height: 1em;
text-align: left;
padding-right: 30vh;
font-family: Manrope, arial;
font-style: normal;
font-weight: normal;
font-size: 5vh;
color: rgba(129,150,143,1);
margin-bottom: 20px;
}
#Line_ {
fill: transparent;
stroke: rgba(129,150,143,1);
stroke-width: 4px;
stroke-linejoin: miter;
stroke-linecap: butt;
stroke-miterlimit: 4;
shape-rendering: auto;
}
.Line_ {
width: 509px;
height: 10px;
transform: matrix(1,0,0,1,0,0);
margin-bottom: 40px;
}
#Midcontainer {
position:absolute;
}
#Mid {
float:bottom;
position:absolute;
}
.MySkills {
position: relative;
overflow:visible;
height: 1em;
text-align: left;
font-family: Manrope, arial;
font-style: normal;
font-weight: lighter;
font-size: 12vh;
color: rgba(129,150,143,1);
letter-spacing: -0.85px;
}
<!DOCTYPE html>
<html>
<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>wbdg portfolio</title>
<link rel="stylesheet" type="text/css" id="applicationStylesheet" href="../faux styles.css"/>
</head>
<body>
<div>
<canvas></canvas>
<script id="jssomething" type="text/javascript" src="../faux scripts.js"></script>
<script src="https://kit.fontawesome.com/4f3ce16e3e.js" crossorigin="anonymous"></script>
<div id="MIDDLEcontainer">
<div id="MIDDLE">
<div id="Good_ideas_can_take_time">
<p>Good ideas can take time.</p>
</div>
<div id="And_execution_takes_even_more">
<span>And execution takes even more.</span>
</div>
<svg class="Line_" viewBox="0 0 674 4">
<path id="Line_" d="M 0 0 L 674 0">
</path>
</svg>
<div id="Midcontainer">
<div id="Mid">
<div class="MySkills"> Photos </div>
<div class="MySkills"> Illustrations </div>
<div class="MySkills"> Videos </div>
<div class="MySkills"> Animations </div>
<div class="MySkills"> Branding </div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If I understand correctly, change these lines in int() function:
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
to this:
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;

Trying to find out why the jumpSouth() function shown in this example breaks the zoom/pan feature, click North and zoom pan is fine, click south = bad

Most of the functionality I need is here, however, when I use scrollIntoView(), this breaks my zoom for some reason. Before I click on one of my buttons to scroll the element into view, you can zoom in/out with the scroll wheel and the zoom follows the pointer location. However, as soon as you click a button to engage scrollIntoView() the zoom function breaks and jumps around like crazy when you use the scroll wheel.
I'm not sure why it is affecting the zoom. I think it may be changing the origin of the transform which is making it act up, but I can't figure out how to change it to make it work. When you click on the north button, the zoom works normally, however, when you click south, the SVG will scroll into view, but the zoom and scroll will be all over the place and it no longer follows the path of the pointer. the code pen can be found below.
https://codepen.io/Cruebee/pen/poLwzNG
// setup below is for setting up the zoom/pan around the map
var scale = 1,
panning = false,
pointX = 0,
pointY = 0,
start = { x: 0, y: 0 },
zoom = document.getElementById("zoom");
function setTransform() {
zoom.style.transform =
"translate(" + pointX + "px," + pointY + "px) scale(" + scale + ")";
}
zoom.onmousedown = function (e) {
e.preventDefault();
start = { x: e.clientX - pointX, y: e.clientY - pointY };
panning = true;
};
zoom.onmouseup = function (e) {
panning = false;
};
zoom.onmousemove = function (e) {
e.preventDefault();
if (!panning) {
return;
}
pointX = e.clientX - start.x;
pointY = e.clientY - start.y;
setTransform();
};
zoom.onwheel = function (e) {
e.preventDefault();
var xs = (e.clientX - pointX) / scale,
ys = (e.clientY - pointY) / scale,
delta = e.wheelDelta ? e.wheelDelta : -e.deltaY;
(delta > 0) ? (scale *= 1.2) : (scale /= 1.2);
pointX = e.clientX - xs * scale;
pointY = e.clientY - ys * scale;
setTransform();
};
// Hide all rooms on page load
let elementBtns = ["north", "south"]
for (let i = 0; i < elementBtns.length; i++) {
// console.log(elementBtns[i]);
document.getElementById(elementBtns[i]).style.display = "none";
}
// hide/show rooms
function hideNorth() {
var style = document.getElementById("north").style.display;
if (style === "none")
(document.getElementById("north").style.display = "block");
else document.getElementById("north").style.display = "none";
}
function hideSouth() {
var style = document.getElementById("south").style.display;
if (style === "none")
document.getElementById("south").style.display = "block";
else document.getElementById("south").style.display = "none";
}
function jumpNorth() {
var element = document.getElementById("north");
element.scrollIntoView();
}
function jumpSouth() {
var element = document.getElementById("south");
element.scrollIntoView();
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: 'Lato', sans-serif;
font-weight: 400;
font-size: 20px;
line-height: 1.6;
background-color: whitesmoke;
color: black;
height: 100%;
width: 100%;
}
p {
font-size: 16px;
padding: 0.5rem;
margin: 0.5rem;
}
h1 {
font-size: 40px;
font-weight: 700;
margin: 0.5rem;
}
.main-title {
text-align: center;
margin: 0;
}
.page-header {
margin: 0.5rem;
}
.floor-plan-wrapper {
display: block;
margin: 0 auto;
border: 1px solid black;
border-radius: 20px;
width: 95%;
height: 600px;
overflow: hidden;
}
.floor-plan {
/* background-image: url(../assets/walls.svg); */
background-repeat: no-repeat;
box-sizing: content-box;
border-radius: 20px;
transform-origin: 0px, 0px;
}
#zoom {
width: 100%;
height: 100%;
transform-origin: 0px 0px;
transform: scale(1) translate(0px, 0px);
cursor: grab;
}
div#zoom {
width: 100%;
height: auto;
}
div#zoom > .floor-plan {
width: 100%;
height: auto;
}
.button-list {
list-style: none;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
margin: 10px;
}
button {
cursor: pointer;
color: green;
margin: 2px;
}
.legend-wrap {
margin: 1rem;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="Generator" content="vscodeĀ®" />
<meta name="Author" content="Cruebee" />
<meta name="Keywords" content="floormap" />
<meta name="Description" content="interactive floor plan" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, height=device-height, initial-scale=1"
/>
<title>Test Mapping</title>
<!--
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudfare.com/ajax/libs/normalize/8.0.1/normalize.min.css"/>
-->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Lato:400, 700&display=swap"
/>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="page-wrapper">
<header class="main-title">
<div id="page-label" data-toggle="collapse">
<h1 class="page-header">Building Map</h1>
</div>
</header>
<div class="legend-wrap">
<h2>Legend</h2>
<p>First floor has red accents. Second floor has green accents. First floor rooms are pink, and second floor rooms are green.</p>
</div>
<ul class="button-list">
<li><button onclick="hideNorth(); jumpNorth()">North</button></li>
<li><button onclick="hideSouth(); jumpSouth()">South</button></li>
</ul>
<div id="outer-zoom" class="floor-plan-wrapper">
<!-- there is an SVG img in the div below -->
<div id="zoom" class="floor-plan">
<p>I removed the SVG img that is imbedded in the code pen to save room</p>
</div>
</div>
</div>
<script src="js/mapInteraction.js"></script>
</body>
</html>

HTML5 Canvas rectangles click coordinates is inconsistent

I made a canvas size as A4, i draw a rectangles inside and when i click the light blue rectangle it will call a function but the coordinates of the click on the rectangle is inconsistent and every row the y level is needed to click more lower then the light blue rectangle.
How i make the coordinates more accurate?
(Code need full screen)
'use strict';
function mmTopx(mm) {
//return mm * 3.7795275591;
//return mm * 3.7795275590551;
return (mm * 96) / 25.4;
}
function cmTopx(cm) {
return cm * 1; /* NEED TO FIX */
}
// Get mouse position
function getMousePos(c, evt) {
var rect = c.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top,
};
}
class sticker {
#width;
#height;
#fullheight;
constructor(width = 1, height = 1, fullheight = 1) {
if (!sticker.isNumber(width) || !sticker.isNumber(height) || !sticker.isNumber(fullheight)) throw 'Only accept number';
this.#width = width;
this.#height = height;
this.#fullheight = fullheight;
}
static isNumber(n) {
return !isNaN(parseFloat(n)) && !isNaN(n - 0) && typeof n != 'string';
}
get size() {
return { width: this.#width, height: this.#height, fullheight: this.#fullheight };
}
get width() {
return this.#width;
}
get height() {
return this.#height;
}
get fullheight() {
return this.#fullheight;
}
set width(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#width = n;
}
set height(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#height = n;
}
set fullheight(n) {
if (!sticker.isNumber(n)) throw 'Only accept number';
this.#fullheight = n;
}
}
window.onload = () => {
const controls = document.querySelectorAll('.control');
const canvas = document.querySelector('.A4');
const canvasPadding = {
left:
window
.getComputedStyle(canvas, null)
.getPropertyValue('padding-left')
.match(/\d+.\d+|\d+/)[0] - 0,
top:
window
.getComputedStyle(canvas, null)
.getPropertyValue('padding-top')
.match(/\d+.\d+|\d+/)[0] - 0,
};
/* ///////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////// */
/* ///// CANVAS ///// */
/* ///////////////////////////////////////////////////// */
/* canvas */
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext('2d');
const _sticker = new sticker(mmTopx(25), mmTopx(12), mmTopx(37));
let Stickers = [];
const drawSticker = (x, y, width, height, fullheight) => {
Stickers.push({
color: '#d8d8d8',
width: width,
height: height,
x: x,
y: y,
clicked: function () {
console.log(`you clicked me, ${this.x} ${this.y}`);
},
});
/* full area */
ctx.fillStyle = '#e8f2f8';
ctx.fillRect(x, y, width, fullheight); // x y width height
/* print area */
ctx.fillStyle = '#d8d8d8';
ctx.fillRect(x, y, width, height, fullheight); // x y width height
};
const render = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Stickers = [];
const size = _sticker.size;
for (let y = 0; y < canvas.height - size.fullheight; y += size.fullheight + 10) {
for (let x = 10; x < canvas.width - size.width; x += size.width + 1) {
drawSticker(x, y, size.width, size.height, size.fullheight);
}
}
};
/* ///////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////// */
/* ///// Event Listeners ///// */
/* ///////////////////////////////////////////////////// */
canvas.addEventListener('updateRender', (event) => {
const lengthType = event.detail.dimensionValue.match(/mm|cm/)[0];
let value = event.detail.dimensionValue.match(/\d+/)[0] - 0;
switch (lengthType) {
case 'cm':
//value = cmTopx(value);
break;
case 'mm':
default:
value = mmTopx(value);
break;
}
/* Set the new sticker size */
switch (event.detail.dimension) {
case 'width':
_sticker.width = value;
break;
case 'height':
_sticker.height = value;
break;
case 'fullheight':
_sticker.fullheight = value;
break;
}
render();
});
const event = new Event('change');
controls.forEach((_control) => {
_control.addEventListener(
'change',
(event) => {
const value = event.target.value;
const name = event.target.name;
const dimension = event.target.getAttribute('data-sticker-dim');
const detail = {};
detail['dimension'] = dimension;
detail['dimensionValue'] = value;
detail['name'] = name;
const updateSticker = new CustomEvent('updateRender', { detail: detail });
canvas.dispatchEvent(updateSticker);
},
true
);
const input = _control.querySelector('input');
input.dispatchEvent(event);
});
/* click event for text input */
canvas.addEventListener('click', function (e) {
e.preventDefault();
let x = parseInt(e.clientX - canvas.offsetLeft - canvasPadding.left);
let y = parseInt(e.clientY - canvas.offsetTop - canvasPadding.top);
if (x >= 0 && y >= 0) {
for (let index = 0; index < Stickers.length; index++) {
const _sticker = Stickers[index];
if (
x >= _sticker.x &&
x <= Math.floor(_sticker.x + _sticker.width) &&
y >= _sticker.y &&
y <= Math.floor(_sticker.y + _sticker.height)
) {
_sticker.clicked();
break;
}
}
}
});
/* ///////////////////////////////////////////////////// */
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
background-color: #fafafa;
}
/* //////////////////////////////////////////////////////////// */
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-self: flex-start;
overflow: auto;
}
/* //////////////////////////////////////////////////////////// */
.container .controllers {
position: sticky;
top: 50%;
transform: translateY(-50%);
width: 250px;
height: 500px;
flex: 0 0 100px;
border-radius: 20px;
box-sizing: border-box;
padding: 20px;
margin-left: 5px;
border: 1px solid #9e9e9e;
}
.container .controllers .control {
position: relative;
flex: 0 0 100%;
height: 50px;
padding: 5px;
}
.container .controllers .control:first-child {
margin-top: 5px;
}
.container .controllers .control:not(:first-child) {
margin-top: 20px;
}
.container .controllers .control label::before {
content: attr(data-placeholder);
position: absolute;
left: 20px;
top: 20px;
color: #65657b;
font-family: sans-serif;
line-height: 14px;
pointer-events: none;
transform-origin: 0 50%;
transition: transform 200ms, color 200ms;
}
.container .controllers .control .cut {
position: absolute;
border-radius: 10px;
height: 20px;
width: fit-content;
left: 20px;
top: -20px;
transform: translateY(0);
transition: transform 200ms;
}
.container .controllers .control input {
height: 100%;
padding: 4px 20px 0;
width: 100%;
background-color: #eeeeee;
border-radius: 12px;
border: 0;
outline: 0;
box-sizing: border-box;
color: #eee;
font-size: 18px;
color: black;
}
.container .controllers .control input:focus ~ .cut,
.container .controllers .control input:not(:placeholder-shown) ~ .cut {
transform: translateY(8px);
}
.container .controllers .control input:focus ~ label::before,
.container .controllers .control input:not(:placeholder-shown) ~ label::before {
content: attr(data-focus-placeholder);
transform: translateY(-30px) translateX(10px) scale(0.75);
}
.container .controllers .control input:not(:placeholder-shown) ~ label::before {
content: attr(data-focus-placeholder);
color: #808097;
}
.container .controllers .control input:focus ~ label::before {
color: #dc2f55;
}
/* //////////////////////////////////////////////////////////// */
.container textarea {
background: none;
outline: none;
}
.container .A4 {
align-self: center;
width: 21cm;
flex: 0 0 29.7cm;
padding: 1cm;
border: 1px #d3d3d3 solid;
border-radius: 5px;
background: #f5f5f5;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
/* //////////////////////////////////////////////////////////// */
#page {
size: A4;
margin: 0;
}
#media print {
html,
body {
height: 99%;
}
.page {
margin: 0;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}
<!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>A4 Render Stickers</title>
</head>
<body>
<div class="container">
<div class="controllers">
<button>print</button>
<div class="control">
<input type="text" value="25mm" data-sticker-dim="width" name="printWidth" placeholder=" " />
<div class="cut"></div>
<label for="printWidth" data-focus-placeholder="Width print" data-placeholder="Width size of print area"></label>
</div>
<div class="control">
<input type="text" value="12mm" data-sticker-dim="height" name="printHeight" placeholder=" " />
<div class="cut"></div>
<label for="printHeight" data-focus-placeholder="Height print" data-placeholder="Height size of print area"></label>
</div>
<div class="control">
<input type="text" value="37mm" data-sticker-dim="fullheight" name="stikcerHeight" placeholder=" " />
<div class="cut"></div>
<label for="stikcerHeight" data-focus-placeholder="Full height sticker" data-placeholder="Height size of full sticker"></label>
</div>
</div>
<canvas width="800" height="800" class="A4"></canvas>
</div>
</body>
</html>

The square does not move JavaScript

I'm creating a game, the div with id "playerDiv" when I hit the space bar it should start going up but it doesn't. So I would like when I hit the space bar the div would go up high.
could you help me? could you also report me the mistakes i made?
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 420 + inc;
player.top = player.top + x;
inc++
playerTimeOut = setTimeout(jump, 50);
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.key === ' ') {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<title>Game</title>
</head>
<body>
<div id="background">
<div id="playerDiv">
</div>
</div>
</body>
<script src="script.js"></script>
</html>
You're not passing the argument in addListener and you're not using correctly the top property, it belongs to style and needs unit , for example px
Also keyCode is deprecated, use key instead
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
player.style.bottom = `${x}px`
inc++
console.log(player.style.bottom)
}
//window.addEventListener("keydown", e => e.key === "(Space Character)" ? jump() : '');
//For snippet only
jump()
setTimeout(() => jump(), 1000)
* {
/* demo */
box-sizing: border-box
}
body {
background-color: #222;
}
#background {
border: solid 2px #ddd;
width: 800px;
height: 500px;
position: relative;
/* demo */
max-width: 100%
}
#playerDiv {
background-color: #aaa;
width: 60px;
height: 80px;
position: absolute;
bottom: 0px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>
Try this:
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
let style = window.getComputedStyle(player);
player.style.top = (parseInt(style.getPropertyValue('top'),10) - x) + 'px';
inc++
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.keyCode == "32") {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>

How to make boxes disappear when clicked in javascript?

So for my final assignment I have to create an interactive website using javascript, canvas, html, and css. So I made boxes for my javascript in my canvas and I want boxes to disappear when I click on them but I don't know how to do it. Can someone help me?
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 5</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<header>
<h1>PART2 - JavaScript and The Canvas</h1>
</header>
<canvas id="canvas" width="1000" height="600"></canvas>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Here is my CSS:
html {
font-size: 14px;
}
header {
background-color: white;
height: 3rem;
text-align: center;
}
h1 {
color: black;
}
h2 {
color:white;
}
body{
background-color: white;
padding-left: 50px;
padding-right: 50px;
}
#canvas {
position: absolute;
top: 8rem;
left: 8rem;
width: 700px;
height: 400px;
background: white;
animation: move 8s ease infinite;
}
#keyframes move {
50% {
transform: translate(600px, 200px);
}
}
Here is my JavaScript
randomBoxes();
function getRandomColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += (Math.random() * 17 | 0).toString(17);
}
return color;
}
function boundryNum(theMin, theMax) {
var theRange = (theMax - theMin) + 5;
var randomNum = Math.floor((Math.random() * theRange) + theMin);
return randomNum;
}
function drawbox() {
var width = Math.floor(Math.random() * 200) +20;
var height = Math.floor(Math.random() * 400) + 20;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillRect(boundryNum(25,800),boundryNum(25,400),width,height);
context.fillStyle = getRandomColor();
}
function randomBoxes(){
var number = Math.floor(Math.random() * 5) + 1;
//Three to six times....
while(number >= 0) {
drawbox();
number--;
}
setInterval(drawbox, 2000)
}
You havn't included any code in your question so I have just made some, the way I understand your question
<div style="left: 30px; top: 30px; border-width: 3px; border-style: solid; border-color: black; width: 150px; height: 100px; display: ;" id="box1" onclick="disappear()">
<h3>Click me</h3>
</div>
<script type="text/javascript">
function disappear() {
document.getElementById("box1").style.display = "none" ;
}
</script>

Categories

Resources