how do i move multipal balls - javascript

how do i add multipel ball to move plss help
here is the code for ball and how it bounces
review it
i think its the obj name thats where the problem
i cant manage to make new name on evry time a new obj
is created
i also tried jquary to add multipal ball ellement
but that also does not work
// code for ball
const INITIAL_VELOCITY = 0.085
const VELOCITY_CHANGE_RATE = 0
class Ball {
constructor(ballElem) {
this.ballElem = ballElem
this.reset()
}
get x() {
return parseFloat(getComputedStyle(this.ballElem).getPropertyValue("--x"))
}
set x(value) {
this.ballElem.style.setProperty("--x", value)
}
get y() {
return parseFloat(getComputedStyle(this.ballElem).getPropertyValue("--y"))
}
set y(value) {
this.ballElem.style.setProperty("--y", value)
}
rect() {
return this.ballElem.getBoundingClientRect()
}
reset() {
this.x = 50
this.y = 50
this.direction = {x : 0}
while (Math.abs(this.direction.x) <= 0.1 || Math.abs(this.direction.x) >= 0.9) {
const heading = randomNumberBetween(0, 2 * Math.PI)
this.direction = { x: Math.cos(heading), y: Math.sin(heading) }
}
this.velocity = INITIAL_VELOCITY
}
update(delta,index) {
console.log(delta,index)
this.x += this.direction.x * this.velocity * delta
this.y += this.direction.y * this.velocity * delta
// this.velocity += VELOCITY_CHANGE_RATE * delta
// this.velocity -= VELOCITY_CHANGE_RATE / delta
const rect = this.rect()
if (rect.bottom >= window.innerHeight || rect.top <= 0) {
this.direction.y *= -1
}
if (rect.right >= window.innerWidth || rect.left <= 0) {
this.direction.x *= -1
}
//background color
const hue = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--hue"));
document.documentElement.style.setProperty("--hue", hue + delta * 0.02)
}
}
function randomNumberBetween(min, max) {
return Math.random() * (max - min) + min
}
var ballarr = []
for(var i = 0; i <= 10; i++){
document.querySelector('body').innerHTML += `<div class="ball" id="ball${i}"></div>`
ballarr[i] = new Ball(document.querySelector(`#ball${i}`))
}
console.log(ballarr)
// const ball = new Ball(document.querySelector("#ball"))
let lastTime
function updateTime(time) {
if (lastTime != null) {
const delta = time - lastTime
ballarr.map((val, index) => {
val.update(delta, index)
})
}
lastTime = time
window.requestAnimationFrame(updateTime)
}
*,
*::after,
*::before {
box-sizing: border-box;
}
:root {
--hue: 200;
--saturation: 50%;
--foreground-color: hsl(var(--hue), var(--saturation), 75%);
--background-color: hsl(var(--hue), var(--saturation), 20%);
}
body {
margin: 0;
overflow: hidden;
}
.ball {
--x: 50;
--y: 50;
position: absolute;
/*background-color: var(--foreground-color); */
/*background-color: #13ecb6;*/
background-color: black;
/*border: 4px solid #13ecb6;*/
left: calc(var(--x) * 1vw);
top: calc(var(--y) * 1vh);
border-radius: 50%;
transform: translate(-50%, -50%);
width: 3vh;
height: 3vh;
}
<div class="ball" id="ball"></div>

The issue is due to how you create the balls and add them to the DOM and your ballarr array:
var ballarr = []
for (var i = 0; i <= 10; i++) {
const ballEl = document.createElement('div');
ballEl.classList.add('ball');
document.body.appendChild(ballEl);
const ball = new Ball(ballEl);
ballarr.push(ball);
}
You also need to use forEach() to loop through the array to update ball positions, not map():
ballarr.forEach(ball => ball.update(delta));
Here's a full working example:
// code for ball
const INITIAL_VELOCITY = 0.085
const VELOCITY_CHANGE_RATE = 0
class Ball {
constructor(ballElem) {
this.ballElem = ballElem
this.reset()
}
get x() {
return parseFloat(getComputedStyle(this.ballElem).getPropertyValue("--x"))
}
set x(value) {
this.ballElem.style.setProperty("--x", value)
}
get y() {
return parseFloat(getComputedStyle(this.ballElem).getPropertyValue("--y"))
}
set y(value) {
this.ballElem.style.setProperty("--y", value)
}
rect() {
return this.ballElem.getBoundingClientRect()
}
reset() {
this.x = 50
this.y = 50
this.direction = {
x: 0
}
while (Math.abs(this.direction.x) <= 0.1 || Math.abs(this.direction.x) >= 0.9) {
const heading = randomNumberBetween(0, 2 * Math.PI)
this.direction = {
x: Math.cos(heading),
y: Math.sin(heading)
}
}
this.velocity = INITIAL_VELOCITY
}
update(delta) {
this.x += this.direction.x * this.velocity * delta
this.y += this.direction.y * this.velocity * delta
const rect = this.rect()
if (rect.bottom >= window.innerHeight || rect.top <= 0) {
this.direction.y *= -1
}
if (rect.right >= window.innerWidth || rect.left <= 0) {
this.direction.x *= -1
}
//background color
const hue = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--hue"));
document.documentElement.style.setProperty("--hue", hue + delta * 0.02)
}
}
function randomNumberBetween(min, max) {
return Math.random() * (max - min) + min
}
var ballarr = []
for (var i = 0; i <= 10; i++) {
const ballEl = document.createElement('div');
ballEl.classList.add('ball');
document.body.appendChild(ballEl);
const ball = new Ball(ballEl);
ballarr.push(ball);
}
let lastTime
function updateTime(time) {
if (lastTime != null) {
const delta = time - lastTime
ballarr.forEach(ball => ball.update(delta));
}
lastTime = time
window.requestAnimationFrame(updateTime)
}
updateTime(lastTime);
*,
*::after,
*::before {
box-sizing: border-box;
}
:root {
--hue: 200;
--saturation: 50%;
--foreground-color: hsl(var(--hue), var(--saturation), 75%);
--background-color: hsl(var(--hue), var(--saturation), 20%);
}
body {
margin: 0;
overflow: hidden;
}
.ball {
--x: 50;
--y: 50;
position: absolute;
/*background-color: var(--foreground-color); */
/*background-color: #13ecb6;*/
background-color: black;
/*border: 4px solid #13ecb6;*/
left: calc(var(--x) * 1vw);
top: calc(var(--y) * 1vh);
border-radius: 50%;
transform: translate(-50%, -50%);
width: 3vh;
height: 3vh;
}

Related

Not able to get the input text box editable inside animated javascript

I have added the code snippet over here. I was trying to do some random exercise. Can someone look why my textbox is not editable. There is falling leaf animation over here. Along with I have added one textbox on top of it. But currently I am not able to add any text to the textbox.
I am just adding more text in order to overcome the error message that the post is mostly having code and not much explanation.
var LeafScene = function(el) {
this.viewport = el;
this.world = document.createElement('div');
this.leaves = [];
this.options = {
numLeaves: 20,
wind: {
magnitude: 1.2,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 0
},
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
// animation helper
this.timer = 0;
this._resetLeaf = function(leaf) {
// place leaf towards the top left
leaf.x = this.width * 2 - Math.random()*this.width*1.75;
leaf.y = -10;
leaf.z = Math.random()*200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = Math.random()*this.height/2;
}
// at the start, the leaf can be anywhere
if (this.timer == 0) {
leaf.y = Math.random()*this.height;
}
// Choose axis of rotation.
// If axis is not X, chose a random static x-rotation for greater variability
leaf.rotation.speed = Math.random()*10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = 'X';
} else if (randomAxis > 0.25) {
leaf.rotation.axis = 'Y';
leaf.rotation.x = Math.random()*180 + 90;
} else {
leaf.rotation.axis = 'Z';
leaf.rotation.x = Math.random()*360 - 180;
// looks weird if the rotation is too fast around this axis
leaf.rotation.speed = Math.random()*3;
}
// random speed
leaf.xSpeedVariation = Math.random() * 0.8 - 0.4;
leaf.ySpeed = Math.random() + 1.5;
return leaf;
}
this._updateLeaf = function(leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = 'translateX( ' + leaf.x + 'px ) translateY( ' + leaf.y + 'px ) translateZ( ' + leaf.z + 'px ) rotate' + leaf.rotation.axis + '( ' + leaf.rotation.value + 'deg )';
if (leaf.rotation.axis !== 'X') {
t += ' rotateX(' + leaf.rotation.x + 'deg)';
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
// reset if out of view
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
}
this._updateWind = function() {
// wind follows a sine curve: asin(b*time + c) + a
// where a = wind magnitude as a function of leaf position, b = wind.duration, c = offset
// wind duration should be related to wind magnitude, e.g. higher windspeed means longer gust duration
if (this.timer === 0 || this.timer > (this.options.wind.start + this.options.wind.duration)) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration = this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function(t, y) {
// should go from full wind speed at the top, to 1/2 speed at the bottom, using leaf Y
var a = this.magnitude/2 * (screenHeight - 2*y/3)/screenHeight;
return a * Math.sin(2*Math.PI/this.duration * t + (3 * Math.PI/2)) + a;
}
}
}
}
LeafScene.prototype.init = function() {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement('div'),
x: 0,
y: 0,
z: 0,
rotation: {
axis: 'X',
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0,
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = 'leaf-scene';
this.viewport.appendChild(this.world);
// set perspective
this.world.style.webkitPerspective = "400px";
this.world.style.MozPerspective = "400px";
this.world.style.oPerspective = "400px";
this.world.style.perspective = "400px";
// reset window height/width on resize
var self = this;
window.onresize = function(event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
}
LeafScene.prototype.render = function() {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
}
// start up leaf scene
var leafContainer = document.querySelector('.falling-leaves'),
leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
body, html {
height: 100%;
}
form {
width: 600px;
margin: 0px auto;
padding: 15px;
}
input[type=text] {
display: block;
padding: 10px;
box-sizing: border-box;
font-size: x-large;
margin-top: 25%;
}
input[type=text] {
width: 100%;
margin-bottom: 15px;
}
.falling-leaves {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 100%;
max-width: 880px;
max-height: 880px; /* image is only 880x880 */
transform: translate(-50%, 0);
border: 20px solid #fff;
border-radius: 50px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/sidebar-bg.png) no-repeat center center;
background-size: cover;
overflow: hidden;
}
.leaf-scene {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
transform-style: preserve-3d;
}
.leaf-scene div {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/leaf.svg) no-repeat;
background-size: 100%;
transform-style: preserve-3d;
backface-visibility: visible;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
</head>
<body>
<div class="falling-leaves">
<form id="frmContact">
<input type="text" id="txtName" name="txtName" placeholder="Text goes here">
</form>
</div>
<script src="script/script.js"></script>
</body>
</html>

Pong ball - high speed results in ball not colliding - Javascript

I'm making a pong ball game in javascript. When the velocity is low, the game works fine and the ball will collide with the paddle. However, when the velocity gets high, the ball will "teleport" through the paddle, because the ball's position is updated this way:
update(delta, playerPad, aiPad) {
this.x += this.direction.x * this.velocity * delta;
this.y += this.direction.y * this.velocity * delta;
}
How can I solve this issue? This caused the game to be unplayable at high speed. Below is my coding snippet
const INIT_VELOCITY = 0.3;
const INCREMENT_VELOCITY = 0.000;
const PI = Math.PI;
class Ball {
constructor(ballElem) {
this.ball = ballElem;
this.reset();
}
get x() {
return parseFloat(getComputedStyle(this.ball).getPropertyValue("--x"));
}
get y() {
return parseFloat(getComputedStyle(this.ball).getPropertyValue("--y"));
}
set x(value) {
this.ball.style.setProperty("--x", value);
}
set y(value) {
this.ball.style.setProperty("--y", value);
}
reset() {
this.x = 50;
this.y = 50;
this.velocity = INIT_VELOCITY;
//setting the direction of the ball
// let angle = Math.random() * 2 * PI;
let angle = 2*PI;
// while (
// (angle > PI / 3 && angle < (2 * PI) / 3) ||
// (angle > (4 * PI) / 3 && angle < (5 * PI) / 3)
// ) {
// angle = Math.random() * 2 * PI;
// }
this.direction = {
x: Math.cos(angle),
y: Math.sin(angle),
};
}
rect() {
return this.ball.getBoundingClientRect();
}
update(delta, playerPad, aiPad) {
this.x += this.direction.x * this.velocity * delta;
this.y += this.direction.y * this.velocity * delta;
this.velocity += INCREMENT_VELOCITY;
const rect = this.rect();
if (rect.top <= 0) {
this.direction.y *= -1;
this.y = 0 + (this.rect().height / 2 / innerHeight) * 100;
}
if (rect.bottom >= innerHeight) {
this.direction.y *= -1;
this.y = ((innerHeight - this.rect().height / 2) / innerHeight) * 100;
}
if(this.isColliding(rect,playerPad.rect())){
this.direction.x *= -1;
this.x = ( playerPad.rect().right + rect.width / 2 ) / innerWidth * 100;
}
if(this.isColliding(rect,aiPad.rect())){
this.direction.x *= -1;
this.x = ( aiPad.rect().left - rect.width / 2 ) / innerWidth * 100;
}
if (rect.left <= 0) {
this.reset();
}
if (rect.right >= innerWidth) {
this.reset();
}
}
isColliding(rect1, rect2) {
// console.log("collision");
return rect1.right >= rect2.left
&& rect1.left <= rect2.right
&& rect1.bottom >= rect2.top
&& rect1.top <= rect2.bottom
}
}
class Paddle {
constructor(padElem){
this.pad = padElem;
}
get y(){
return getComputedStyle(this.y).getPropertyValue("--y");
}
set y(value){
this.pad.style.setProperty("--y",value);
}
rect(){
return this.pad.getBoundingClientRect();
}
}
const ball = new Ball(document.querySelector("#ball"));
const playerPad = new Paddle(document.querySelector("#player-pad"));
const aiPad = new Paddle(document.querySelector("#ai-pad"));
let lastTime = 0;
function update(time){
const delta = time - lastTime;
lastTime = time;
ball.update(delta,playerPad,aiPad);
aiPad.y = ball.y;
requestAnimationFrame(update);
}
requestAnimationFrame(update);
document.addEventListener("mousemove",e=>{
playerPad.y = e.y / innerHeight * 100;
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--paddle-color: white;
--ball-color: white;
}
body {
background-color: black;
overflow: hidden;
}
#ball {
--x: 50;
--y: 50;
position: absolute;
top: calc(var(--y)*1vh);
left: calc(var(--x)*1vw);
transform: translate(-50%,-50%);
width: calc(1vw + 1rem);
height: calc(1vw + 1rem);
background-color: var(--ball-color);
border-radius: 50%;
}
.paddle {
--y: 50;
position: absolute;
width: 5px;
height: 15vh;
background-color: var(--paddle-color);
border-radius: 2rem;
top: calc(var(--y)*1vh);
transform: translate(0,-50%);
}
#player-pad {
left: 4px;
}
#ai-pad {
right: 4px;
}
<!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>Pong Ball Clone</title>
<link href="./index.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="ball"></div>
<div class="paddle" id="player-pad"></div>
<div class="paddle" id="ai-pad"></div>
<script src="./script.js" type="module"></script>
</body>
</html>

Cannot read properties of null (reading 'animate') error chrome JS animation

I am new to webdev and I am trying to use this CodePen to animate my buttons:
https://codepen.io/Mamboleoo/pen/JjdXPgR
However, I am still getting this error on chrome when trying to run the code:
Uncaught TypeError: Cannot read properties of null (reading 'animate')
I tried replacing the last JS line to: if ( document.getElementByID("aaa").animate ){} but no success.enter code here
Can anyone help me please ?
HTML
<div class="contianer">
<div class="wrapper" id="aaa">
<button data-type="square">Square particles</button>
<button data-type="emoji">Emoji particles</button>
<button data-type="mario">Mario particles</button>
<button data-type="shadow">Shadow particles</button>
<button data-type="line">Line particles</button>
</div>
<span class="preloader"></span>
</div>
CSS
particle {
position: fixed;
top: 0;
left: 0;
opacity: 0;
pointer-events: none;
background-repeat: no-repeat;
background-size: contain;
}
.wrapper {
position: absolute;
}
.wrapper button {
padding: 20px;
margin: 10px;
align-self: center;
}
.preloader {
position: absolute;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/127738/mario-face.png);
}
JS:
function pop (e) {
let amount = 30;
switch (e.target.dataset.type) {
case 'shadow':
case 'line':
amount = 60;
break;
}
// Quick check if user clicked the button using a keyboard
if (e.clientX === 0 && e.clientY === 0) {
const bbox = e.target.getBoundingClientRect();
const x = bbox.left + bbox.width / 2;
const y = bbox.top + bbox.height / 2;
for (let i = 0; i < 30; i++) {
// We call the function createParticle 30 times
// We pass the coordinates of the button for x & y values
createParticle(x, y, e.target.dataset.type);
}
} else {
for (let i = 0; i < amount; i++) {
createParticle(e.clientX, e.clientY + window.scrollY, e.target.dataset.type);
}
}
}
function createParticle (x, y, type) {
const particle = document.createElement('particle');
document.body.appendChild(particle);
let width = Math.floor(Math.random() * 30 + 8);
let height = width;
let destinationX = (Math.random() - 0.5) * 300;
let destinationY = (Math.random() - 0.5) * 300;
let rotation = Math.random() * 520;
let delay = Math.random() * 200;
switch (type) {
case 'square':
particle.style.background = `hsl(${Math.random() * 90 + 270}, 70%, 60%)`;
particle.style.border = '1px solid white';
break;
case 'emoji':
particle.innerHTML = ['โค','๐Ÿงก','๐Ÿ’›','๐Ÿ’š','๐Ÿ’™','๐Ÿ’œ','๐ŸคŽ'][Math.floor(Math.random() * 7)];
particle.style.fontSize = `${Math.random() * 24 + 10}px`;
width = height = 'auto';
break;
case 'mario':
particle.style.backgroundImage = 'url(https://s3-us-west-
2.amazonaws.com/s.cdpn.io/127738/mario-face.png)';
break;
case 'shadow':
var color = `hsl(${Math.random() * 90 + 90}, 70%, 50%)`;
particle.style.boxShadow = `0 0 ${Math.floor(Math.random() * 10 + 10)}px ${color}`;
particle.style.background = color;
particle.style.borderRadius = '50%';
width = height = Math.random() * 5 + 4;
break;
case 'line':
var color = `hsl(${Math.random() * 90 + 90}, 70%, 50%)`;
particle.style.background = 'black';
height = 1;
rotation += 1000;
delay = Math.random() * 1000;
break;
}
particle.style.width = `${width}px`;
particle.style.height = `${height}px`;
const animation = particle.animate([
{
transform: `translate(-50%, -50%) translate(${x}px, ${y}px) rotate(0deg)`,
opacity: 1
},
{
transform: `translate(-50%, -50%) translate(${x + destinationX}px, ${y + destinationY}px)
rotate(${rotation}deg)`,
opacity: 0
}
], {
duration: Math.random() * 1000 + 5000,
easing: 'cubic-bezier(0, .9, .57, 1)',
delay: delay
});
animation.onfinish = removeParticle;
}
function removeParticle (e) {
e.srcElement.effect.target.remove();
}
if (document.body.animate) {
document.querySelectorAll('button').forEach(button => button.addEventListener('click', pop));
}

How do i add a link to this animated button

Essentially i found this button that i wanted to add to my wixsite that links to a store. I have gotten the button animation to work and this button exists as a html element on wix. But all the button does currently is do the animation and dosent link. Could someone edit this code so after the animation plays the user will be redirected to a certain link.
I've tried looking up link code and inserting it in logical places to determine where it might work but obviously i dident find anything. And even if it did it likely would have redirected before the animation finished.
Here is the code without any of my attempts to try and fix this problem.
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
Math.randMinMax = function (min, max, round) {
var val = min + (Math.random() * (max - min));
if (round) val = Math.round(val);
return val;
};
Math.TO_RAD = Math.PI / 180;
Math.getAngle = function (x1, y1, x2, y2) {
var dx = x1 - x2,
dy = y1 - y2;
return Math.atan2(dy, dx);
};
Math.getDistance = function (x1, y1, x2, y2) {
var xs = x2 - x1,
ys = y2 - y1;
xs *= xs;
ys *= ys;
return Math.sqrt(xs + ys);
};
var FX = {};
(function () {
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
lastUpdate = new Date(),
mouseUpdate = new Date(),
lastMouse = [],
width, height;
FX.particles = [];
setFullscreen();
document.getElementById('button').addEventListener('mousedown', buttonEffect);
function buttonEffect() {
var button = document.getElementById('button'),
height = button.offsetHeight,
left = button.offsetLeft,
top = button.offsetTop,
width = button.offsetWidth,
x, y, degree;
for (var i = 0; i < 40; i = i + 1) {
if (Math.random() < 0.5) {
y = Math.randMinMax(top, top + height);
if (Math.random() < 0.5) {
x = left;
degree = Math.randMinMax(-45, 45);
} else {
x = left + width;
degree = Math.randMinMax(135, 225);
}
} else {
x = Math.randMinMax(left, left + width);
if (Math.random() < 0.5) {
y = top;
degree = Math.randMinMax(45, 135);
} else {
y = top + height;
degree = Math.randMinMax(-135, -45);
}
}
createParticle({
x: x,
y: y,
degree: degree,
speed: Math.randMinMax(100, 150),
vs: Math.randMinMax(-4, -1)
});
}
}
window.setTimeout(buttonEffect, 100);
loop();
window.addEventListener('resize', setFullscreen);
function createParticle(args) {
var options = {
x: width / 2,
y: height / 2,
color: 'hsla(' + Math.randMinMax(160, 290) + ', 100%, 50%, ' + (Math.random().toFixed(2)) + ')',
degree: Math.randMinMax(0, 360),
speed: Math.randMinMax(300, 350),
vd: Math.randMinMax(-90, 90),
vs: Math.randMinMax(-8, -5)
};
for (key in args) {
options[key] = args[key];
}
FX.particles.push(options);
}
function loop() {
var thisUpdate = new Date(),
delta = (lastUpdate - thisUpdate) / 1000,
amount = FX.particles.length,
size = 2,
i = 0,
p;
ctx.fillStyle = 'rgba(15,15,15,0.25)';
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeStyle = 'lighter';
for (; i < amount; i = i + 1) {
p = FX.particles[i];
p.degree += (p.vd * delta);
p.speed += (p.vs);// * delta);
if (p.speed < 0) continue;
p.x += Math.cos(p.degree * Math.TO_RAD) * (p.speed * delta);
p.y += Math.sin(p.degree * Math.TO_RAD) * (p.speed * delta);
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate(p.degree * Math.TO_RAD);
ctx.fillStyle = p.color;
ctx.fillRect(-size, -size, size * 2, size * 2);
ctx.restore();
}
lastUpdate = thisUpdate;
requestAnimFrame(loop);
}
function setFullscreen() {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
};
})();
body {
margin: 0;
overflow: hidden;
}
#myCanvas {
display: block;
}
#button {
font-family: "Gill Sans", "Gill Sans MT", Calibri, sans-serif;
position: absolute;
font-size: 1.5em;
text-transform: uppercase;
padding: 7px 20px;
left: 50%;
width: 200px;
margin-left: -100px;
top: 50%;
border-radius: 10px;
color: white;
text-shadow: -1px -1px 1px rgba(0,0,0,0.8);
border: 5px solid transparent;
border-bottom-color: rgba(0,0,0,0.35);
background: hsla(260, 100%, 50%, 1);
cursor: pointer;
outline: 0 !important;
animation: pulse 1s infinite alternate;
transition: background 0.4s, border 0.2s, margin 0.2s;
}
#button:hover {
background: hsla(220, 100%, 60%, 1);
margin-top: -1px;
animation: none;
}
#button:active {
border-bottom-width: 0;
margin-top: 5px;
}
#keyframes pulse {
0% {
margin-top: 0px;
}
100% {
margin-top: 6px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="button">Donate</button>
<canvas id="myCanvas" width="500" height="500"></canvas>
</body>
</html>
So again the expected result is to play the animation for the button then redirect to another page and the current result is the button simply playing the animation when clicked. If anyone could please write this code it would be super helpful.
Try changing your button to a href link. You may have to add some extra styling to the id class, but this should work.
<a id="button" href="https://www.linktosite.com">Link Button</a>
Put this on the button html tag onclick="location.href='http://www.link.com'"
You should add an activity when click on button. For example:
<button id="button" onclick="window.location.href = 'https://www.google.com';">Donate</button>
Demo:
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
Math.randMinMax = function (min, max, round) {
var val = min + (Math.random() * (max - min));
if (round) val = Math.round(val);
return val;
};
Math.TO_RAD = Math.PI / 180;
Math.getAngle = function (x1, y1, x2, y2) {
var dx = x1 - x2,
dy = y1 - y2;
return Math.atan2(dy, dx);
};
Math.getDistance = function (x1, y1, x2, y2) {
var xs = x2 - x1,
ys = y2 - y1;
xs *= xs;
ys *= ys;
return Math.sqrt(xs + ys);
};
var FX = {};
(function () {
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
lastUpdate = new Date(),
mouseUpdate = new Date(),
lastMouse = [],
width, height;
FX.particles = [];
setFullscreen();
document.getElementById('button').addEventListener('mousedown', buttonEffect);
function buttonEffect() {
var button = document.getElementById('button'),
height = button.offsetHeight,
left = button.offsetLeft,
top = button.offsetTop,
width = button.offsetWidth,
x, y, degree;
for (var i = 0; i < 40; i = i + 1) {
if (Math.random() < 0.5) {
y = Math.randMinMax(top, top + height);
if (Math.random() < 0.5) {
x = left;
degree = Math.randMinMax(-45, 45);
} else {
x = left + width;
degree = Math.randMinMax(135, 225);
}
} else {
x = Math.randMinMax(left, left + width);
if (Math.random() < 0.5) {
y = top;
degree = Math.randMinMax(45, 135);
} else {
y = top + height;
degree = Math.randMinMax(-135, -45);
}
}
createParticle({
x: x,
y: y,
degree: degree,
speed: Math.randMinMax(100, 150),
vs: Math.randMinMax(-4, -1)
});
}
}
window.setTimeout(buttonEffect, 100);
loop();
window.addEventListener('resize', setFullscreen);
function createParticle(args) {
var options = {
x: width / 2,
y: height / 2,
color: 'hsla(' + Math.randMinMax(160, 290) + ', 100%, 50%, ' + (Math.random().toFixed(2)) + ')',
degree: Math.randMinMax(0, 360),
speed: Math.randMinMax(300, 350),
vd: Math.randMinMax(-90, 90),
vs: Math.randMinMax(-8, -5)
};
for (key in args) {
options[key] = args[key];
}
FX.particles.push(options);
}
function loop() {
var thisUpdate = new Date(),
delta = (lastUpdate - thisUpdate) / 1000,
amount = FX.particles.length,
size = 2,
i = 0,
p;
ctx.fillStyle = 'rgba(15,15,15,0.25)';
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeStyle = 'lighter';
for (; i < amount; i = i + 1) {
p = FX.particles[i];
p.degree += (p.vd * delta);
p.speed += (p.vs);// * delta);
if (p.speed < 0) continue;
p.x += Math.cos(p.degree * Math.TO_RAD) * (p.speed * delta);
p.y += Math.sin(p.degree * Math.TO_RAD) * (p.speed * delta);
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate(p.degree * Math.TO_RAD);
ctx.fillStyle = p.color;
ctx.fillRect(-size, -size, size * 2, size * 2);
ctx.restore();
}
lastUpdate = thisUpdate;
requestAnimFrame(loop);
}
function setFullscreen() {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
};
})();
body {
margin: 0;
overflow: hidden;
}
#myCanvas {
display: block;
}
#button {
font-family: "Gill Sans", "Gill Sans MT", Calibri, sans-serif;
position: absolute;
font-size: 1.5em;
text-transform: uppercase;
padding: 7px 20px;
left: 50%;
width: 200px;
margin-left: -100px;
top: 50%;
border-radius: 10px;
color: white;
text-shadow: -1px -1px 1px rgba(0,0,0,0.8);
border: 5px solid transparent;
border-bottom-color: rgba(0,0,0,0.35);
background: hsla(260, 100%, 50%, 1);
cursor: pointer;
outline: 0 !important;
animation: pulse 1s infinite alternate;
transition: background 0.4s, border 0.2s, margin 0.2s;
}
#button:hover {
background: hsla(220, 100%, 60%, 1);
margin-top: -1px;
animation: none;
}
#button:active {
border-bottom-width: 0;
margin-top: 5px;
}
#keyframes pulse {
0% {
margin-top: 0px;
}
100% {
margin-top: 6px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="button" onclick="window.location.href = 'https://www.google.com';">Donate</button>
<canvas id="myCanvas" width="500" height="500"></canvas>
</body>
</html>

Can't draw canvas

I have a few problem with html5. I created a new webpage and add canvas at the middle of that page.Then created new js file that have a script for canvas and import it to webpage but webpage's canvas still nothing happen.
This is my code. index.html in root folder, style.css in css/ , script.js in js/
function startnewgame(){
score =0;
player.hp =10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount =0;
enemylist ={} ;
bulletlist ={};
upgradelist ={};
randomspwanenemy();
}
function update(){
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillText("Score = "+score,200,30);
score ++;
frameCount++;
if(frameCount % 100 === 0)random
spwanenemy();
if(frameCount % 75 === 0)randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for(var i in bulletlist){
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false ;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i],enemylist[j]);
if(cod){
toRemove = true;
delete enemylist[j];
score+=1000;
break;
}
}
if(toRemove)delete bulletlist[i];
}
for(var i in upgradelist){
updateplayer(upgradelist[i]);
var temp = getdistant(player,upgradelist[i]);
if(temp){
if(upgradelist[i].type === 'score'){
score += 100;
}
if(upgradelist[i].type ==='atkspd'){
player.atkspd +=5;
}
delete upgradelist[i];
}
}
for(var i in enemylist){
updateplayer(enemylist[i]);
var temp = getdistant(player,enemylist[i]);
death(temp);
}
}
function drawplayer(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
ctx.fillText("HP = "+player.hp,20,30);
ctx.fillText("bullet = "+player.attackcounter,20,80);
}
function drawenemy(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
}
function updateplayer(x){
if(x.x+x.width/2>=WIDTH){
x.x=WIDTH-x.width/2;
x.spdX=-x.spdX;
}
if(x.x-x.width/2<=0){
x.x = x.width/2;
x.spdX=-x.spdX;
}
if(x.y+x.height/2>=HEIGHT){
x.y = HEIGHT-x.height/2;
x.spdY=-x.spdY;
}
if(x.y-x.height/2<=0){
x.y = x.height/2;
x.spdY=-x.spdY;
}
x.x+=x.spdX;
x.y+=x.spdY;
drawenemy(x);
}
function adde(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'red'
};
enemylist[id]= earth;
}
function addupgrade(id,x,y,spdX,spdY,width,height,color,type){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : color,
type : type
};
upgradelist[id]= earth;
}
function addbullet(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'black',
timer: 0
};
bulletlist[id]= earth;
}
function getdistant(earth1,earth2){
var rect1 ={
x:earth1.x-earth1.width/2,
y:earth1.y-earth1.height/2,
width:earth1.width,
height:earth1.height
};
var rect2 ={
x:earth2.x-earth2.width/2,
y:earth2.y-earth2.height/2,
width:earth2.width,
height:earth2.height
};
return testcol(rect1,rect2);
}
function death(x){
if(x){
player.hp -= 1;
if(player.hp == 0){
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score "+ score );
startnewgame();
}
}
}
function randomspwanenemy(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 +Math.random()*30;
var width= 10 + Math.random()*30;
var spdY = Math.random()*5 +5;
var spdX = Math.random()*5 +5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id,x,y,spdX,spdY,width,height);
}
function randomspwanupgrade(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 ;
var width= 10 ;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if(sample >0.5){
var type = 'score';
var color ='lightblue';
}
else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id,x,y,spdX,spdY,width,height,color,type);
}
function randomspwanbullet(earth,overangle){
var x = player.x;
var y = player.y;
var height = 10 ;
var width= 10 ;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle)*10 );
var spdX = (Math.cos(angle)*10 );
var id = Math.random();
addbullet(id,x,y,spdX,spdY,width,height);
}
function testcol(earth1,earth2){
var lasthit = Date.now()-timewhenlasthit;
if( earth1.x <= earth2.x+earth2.width
&& earth2.x <= earth1.x+earth1.width
&& earth1.y <= earth2.y+earth2.height
&& earth2.y <= earth1.y+earth1.height
&& lasthit >= 1000)
{
timewhenlasthit=Date.now();
return 1;
}
}
function pp(x){
if(x>0.5)return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount =0;
ctx.font = '30 px Arial';
var score =0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse){
var mouseX = mouse.clientX- document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY-document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY,mouseX) ;
/* if(mouseX <player.width/2)mouseX=player.width/2;
if(mouseX>WIDTH-player.width/2)mouseX = WIDTH-player.width/2;
if(mouseY<player.height/2)mouseY=player.height/2;
if(mouseY>HEIGHT-player.height/2)mouseY = HEIGHT-player.height/2;
player.x = mouseX;
player.y = mouseY;*/
}
document.onclick = function(mouse){
if (player.attackcounter > 25) {
randomspwanbullet(player,player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse){
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player,i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event){
if (event.keyCode===68) {
player.pressingRight = true;
}
else if (event.keyCode===83) {
player.pressingDown = true ;
}
else if (event.keyCode===65) {
player.pressingLeft = true ;
}
else if (event.keyCode===87) {
player.pressingUp = true ;
}
}
document.onkeyup = function(event){
if (event.keyCode===68) {
player.pressingRight = false;
}
else if (event.keyCode===83) {
player.pressingDown = false ;
}
else if (event.keyCode===65) {
player.pressingLeft = false ;
}
else if (event.keyCode===87) {
player.pressingUp = false ;
}
}
function updateplayerposition() {
if(player.pressingRight)player.x+=10
if(player.pressingLeft)player.x-=10
if(player.pressingUp)player.y-=10
if(player.pressingDown)player.y+=10
if(player.x <player.width/2)player.x=player.width/2;
if(player.x>WIDTH-player.width/2)player.x = WIDTH-player.width/2;
if(player.y<player.height/2)player.y=player.height/2;
if(player.y>HEIGHT-player.height/2)player.y = HEIGHT-player.height/2;
}
var player = {
name :'E' ,
x : 40 ,
spdX : 30 ,
y : 40 ,
spdY : 5 ,
hp : 10 ,
width : 20 ,
height : 20,
atkspd : 1,
color : 'green',
attackcounter : 0,
pressingDown : false,
pressingUp : false,
pressingLeft : false,
pressingRight : false,
aimAngle : 0
};
var enemylist ={};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update,40);
}
#header{
background: #202020 ;
font-size: 36px;
text-align: center;
padding:0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx{
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu{
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2{
text-align: center;
font-size: 30px;
}
nav#leftmenu ul{
list-style: none;
padding: 0;
}
nav#leftmenu li{
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a{
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id ="ctx" width ="800" height="600" style = "border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game</li>
<li>Pause Game</li>
<li>Option</li>
<li>End it now</li>
</ul>
</nav>
</section>
</body>
</html>
Ps. this ti my first post,Sorry if I did something wrong.
Edit: canvas id from canvas to ctx
Here's a snippet that's working and drawing correctly. It was just a little typo in the update function, writing it like:
if (frameCount % 100 === 0) random
spwanenemy();
instead of:
if (frameCount % 100 === 0) randomspwanenemy();
So, yea, just a little typo! Understanding errors from the developer console (F12) and spotting what's wrong is a vital skill. Keep practicing!
function startnewgame() {
score = 0;
player.hp = 10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount = 0;
enemylist = {};
bulletlist = {};
upgradelist = {};
randomspwanenemy();
}
function update() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.fillText("Score = " + score, 200, 30);
score++;
frameCount++;
if (frameCount % 100 === 0) randomspwanenemy();
if (frameCount % 75 === 0) randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for (var i in bulletlist) {
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i], enemylist[j]);
if (cod) {
toRemove = true;
delete enemylist[j];
score += 1000;
break;
}
}
if (toRemove) delete bulletlist[i];
}
for (var i in upgradelist) {
updateplayer(upgradelist[i]);
var temp = getdistant(player, upgradelist[i]);
if (temp) {
if (upgradelist[i].type === 'score') {
score += 100;
}
if (upgradelist[i].type === 'atkspd') {
player.atkspd += 5;
}
delete upgradelist[i];
}
}
for (var i in enemylist) {
updateplayer(enemylist[i]);
var temp = getdistant(player, enemylist[i]);
death(temp);
}
}
function drawplayer(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
ctx.fillText("HP = " + player.hp, 20, 30);
ctx.fillText("bullet = " + player.attackcounter, 20, 80);
}
function drawenemy(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
}
function updateplayer(x) {
if (x.x + x.width / 2 >= WIDTH) {
x.x = WIDTH - x.width / 2;
x.spdX = -x.spdX;
}
if (x.x - x.width / 2 <= 0) {
x.x = x.width / 2;
x.spdX = -x.spdX;
}
if (x.y + x.height / 2 >= HEIGHT) {
x.y = HEIGHT - x.height / 2;
x.spdY = -x.spdY;
}
if (x.y - x.height / 2 <= 0) {
x.y = x.height / 2;
x.spdY = -x.spdY;
}
x.x += x.spdX;
x.y += x.spdY;
drawenemy(x);
}
function adde(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'red'
};
enemylist[id] = earth;
}
function addupgrade(id, x, y, spdX, spdY, width, height, color, type) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: color,
type: type
};
upgradelist[id] = earth;
}
function addbullet(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'black',
timer: 0
};
bulletlist[id] = earth;
}
function getdistant(earth1, earth2) {
var rect1 = {
x: earth1.x - earth1.width / 2,
y: earth1.y - earth1.height / 2,
width: earth1.width,
height: earth1.height
};
var rect2 = {
x: earth2.x - earth2.width / 2,
y: earth2.y - earth2.height / 2,
width: earth2.width,
height: earth2.height
};
return testcol(rect1, rect2);
}
function death(x) {
if (x) {
player.hp -= 1;
if (player.hp == 0) {
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score " + score);
startnewgame();
}
}
}
function randomspwanenemy() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10 + Math.random() * 30;
var width = 10 + Math.random() * 30;
var spdY = Math.random() * 5 + 5;
var spdX = Math.random() * 5 + 5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id, x, y, spdX, spdY, width, height);
}
function randomspwanupgrade() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10;
var width = 10;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if (sample > 0.5) {
var type = 'score';
var color = 'lightblue';
} else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id, x, y, spdX, spdY, width, height, color, type);
}
function randomspwanbullet(earth, overangle) {
var x = player.x;
var y = player.y;
var height = 10;
var width = 10;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle) * 10);
var spdX = (Math.cos(angle) * 10);
var id = Math.random();
addbullet(id, x, y, spdX, spdY, width, height);
}
function testcol(earth1, earth2) {
var lasthit = Date.now() - timewhenlasthit;
if (earth1.x <= earth2.x + earth2.width && earth2.x <= earth1.x + earth1.width && earth1.y <= earth2.y + earth2.height && earth2.y <= earth1.y + earth1.height && lasthit >= 1000) {
timewhenlasthit = Date.now();
return 1;
}
}
function pp(x) {
if (x > 0.5) return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount = 0;
ctx.font = '30 px Arial';
var score = 0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse) {
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY, mouseX);
/* if(mouseX <player.width/2)mouseX=player.width/2;
if(mouseX>WIDTH-player.width/2)mouseX = WIDTH-player.width/2;
if(mouseY<player.height/2)mouseY=player.height/2;
if(mouseY>HEIGHT-player.height/2)mouseY = HEIGHT-player.height/2;
player.x = mouseX;
player.y = mouseY;*/
}
document.onclick = function(mouse) {
if (player.attackcounter > 25) {
randomspwanbullet(player, player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse) {
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player, i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event) {
if (event.keyCode === 68) {
player.pressingRight = true;
} else if (event.keyCode === 83) {
player.pressingDown = true;
} else if (event.keyCode === 65) {
player.pressingLeft = true;
} else if (event.keyCode === 87) {
player.pressingUp = true;
}
}
document.onkeyup = function(event) {
if (event.keyCode === 68) {
player.pressingRight = false;
} else if (event.keyCode === 83) {
player.pressingDown = false;
} else if (event.keyCode === 65) {
player.pressingLeft = false;
} else if (event.keyCode === 87) {
player.pressingUp = false;
}
}
function updateplayerposition() {
if (player.pressingRight) player.x += 10
if (player.pressingLeft) player.x -= 10
if (player.pressingUp) player.y -= 10
if (player.pressingDown) player.y += 10
if (player.x < player.width / 2) player.x = player.width / 2;
if (player.x > WIDTH - player.width / 2) player.x = WIDTH - player.width / 2;
if (player.y < player.height / 2) player.y = player.height / 2;
if (player.y > HEIGHT - player.height / 2) player.y = HEIGHT - player.height / 2;
}
var player = {
name: 'E',
x: 40,
spdX: 30,
y: 40,
spdY: 5,
hp: 10,
width: 20,
height: 20,
atkspd: 1,
color: 'green',
attackcounter: 0,
pressingDown: false,
pressingUp: false,
pressingLeft: false,
pressingRight: false,
aimAngle: 0
};
var enemylist = {};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update, 40);
}
#header {
background: #202020;
font-size: 36px;
text-align: center;
padding: 0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx {
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu {
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2 {
text-align: center;
font-size: 30px;
}
nav#leftmenu ul {
list-style: none;
padding: 0;
}
nav#leftmenu li {
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a {
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id="ctx" width="800" height="600" style="border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game
</li>
<li>Pause Game
</li>
<li>Option
</li>
<li>End it now
</li>
</ul>
</nav>
</section>
</body>
</html>

Categories

Resources