<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pong Game by Zach</title>
<style>
canvas {
display: block;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<script>
function playGame(form) {
var canvas;
var ctx;
var keystate;
var canvasWidth = form.cWidth.value;
var canvasHeight = form.cHeight.value;
var ballSpeed = form.bSpeed.value;
var playerSpeed = form.pSpeed.value;
var playerWidth = form.pWidth.value;
var playerHeight = form.pHeight.value;
var movePlayer1Up = form.movePlayer1Up.value.charCodeAt(0) - 32;
var movePlayer1Down = form.movePlayer1Down.value.charCodeAt(0) - 32;
if (form.movePlayer2Up.value == "UpArrow") {
var movePlayer2Up = 38;
} else {
var movePlayer2Up = form.movePlayer2Up.value.charCodeAt(0) - 32;
}
if (form.movePlayer2Down.value == "DownArrow") {
var movePlayer2Down = 40;
} else {
var movePlayer2Down = form.movePlayer2Down.value.charCodeAt(0) - 32;
}
var player1 = {
x: null,
y: null,
score: null,
width: playerWidth,
height: playerHeight,
update: function() {
if (keystate[movePlayer1Up]) this.y -= playerSpeed;
if (keystate[movePlayer1Down]) this.y -= -playerSpeed;
this.y = Math.max(Math.min(this.y, canvasHeight - this.height), 0);
},
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
var player2 = {
x: null,
y: null,
score: null,
width: playerWidth,
height: playerHeight,
update: function() {
if (keystate[movePlayer2Up]) this.y -= 7;
if (keystate[movePlayer2Down]) this.y += 7;
this.y = Math.max(Math.min(this.y, canvasHeight - this.height), 0);
},
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
var ball = {
x: null,
y: null,
vel: null,
side: 20,
serve: function(side) {
var r = Math.random();
this.x = canvasWidth / 2;
this.y = (canvasHeight - this.side) * r;
var phi = 0.1 * Math.PI * (1 - 2 * r);
this.vel = {
x: side * ballSpeed * Math.cos(phi),
y: ballSpeed * Math.sin(phi)
}
},
update: function() {
this.x += this.vel.x;
this.y += this.vel.y;
if (0 > this.y || this.y + this.side > canvasHeight) {
var offset = this.vel.y < 0 ? 0 - this.y : canvasHeight - (this.y + this.side);
this.y += 2 * offset;
this.vel.y *= -1;
}
var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx + bw && ay < by + bh && bx < ax + aw && by < ay + ah;
};
var pdle = this.vel.x < 0 ? player1 : player2;
if (AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height,
this.x, this.y, this.side, this.side)) {
this.x = pdle === player1 ? player1.x + player1.width : player2.x - this.side;
var n = (this.y + this.side - pdle.y) / (pdle.height + this.side);
var phi = 0.25 * Math.PI * (2 * n - 1);
var smash = Math.abs(phi) > 0.2 * Math.PI ? 1.5 : 1;
this.vel.x = smash * (pdle === player1 ? 1 : -1) * ballSpeed * Math.cos(phi);
this.vel.y = smash * ballSpeed * Math.sin(phi);
}
if (0 > this.x + this.side || this.x > canvasWidth) {
ballSpeed = 12;
var isplayer1 = pdle === player1;
player1.score += isplayer1 ? 0 : 1;
player2.score += isplayer1 ? 1 : 0;
this.serve(pdle === player1 ? 1 : -1);
}
},
draw: function() {
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
function mplayer2n() {
canvas = document.createElement("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
player1.x = player1.width;
player1.y = (canvasHeight - player1.height) / 2;
player2.x = canvasWidth - (player1.width + player2.width);
player2.y = (canvasHeight - player2.height) / 2;
player1.score = 0;
player2.score = 0;
ball.serve(1);
}
function update() {
if (player1.score < 10 && player2.score < 10) {
ball.update();
player1.update();
player2.update();
}
}
function draw() {
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.save();
ctx.fillStyle = "red";
player1.draw();
ctx.fillStyle = "blue";
player2.draw();
ctx.fillStyle = "white";
ball.draw();
var w = 4;
var x = (canvasWidth - w) * 0.5;
var y = 0;
var step = canvasHeight / 20;
while (y < canvasHeight) {
ctx.fillStyle = "white"
ctx.fillRect(x, y + step * 0.25, w, step * 0.5);
y += step;
}
ctx.font = "150px Georgia"
var t = player1.score
var v = player2.score
ctx.fillText(t, canvas.width / 2 - ctx.measureText(t).width - 20, 100);
ctx.fillText(v, canvas.width / 2 + 20, 100)
if (player1.score > 9) {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = "Black"
ctx.font = "100px Georgia"
var u = t + " - " + v
var w = "Player 1 wins"
ctx.fillText(w, canvas.width / 2 - ctx.measureText(w).width / 2, 130);
ctx.font = "150px Georgia"
ctx.fillText(u, canvas.width / 2 - ctx.measureText(u).width / 2, 300);
} else if (player2.score > 9) {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = "Black"
ctx.font = "100px Georgia"
var u = t + " - " + v
var w = "Player 2 wins"
ctx.fillText(w, canvas.width / 2 - ctx.measureText(w).width / 2, 130);
ctx.font = "150px Georgia"
ctx.fillText(u, canvas.width / 2 - ctx.measureText(u).width / 2, 300);
}
ctx.restore();
}
mplayer2n();
}
</script>
<form action="">
Settings:
<br>Canvas Width:
<br>
<input type="text" name="cWidth" value="1200">
<br>Canvas Height:
<br>
<input type="text" name="cHeight" value="600">
<br>Ball Speed:
<br>
<input type="text" name="bSpeed" value="12">
<br>Player Speed:
<br>
<input type="text" name="pSpeed" value="8">
<br>Player Width:
<br>
<input type="text" name="pWidth" value="20">
<br>Player Height:
<br>
<input type="text" name="pHeight" value="100">
<br>Move Player 1 Up:
<br>
<input type="text" name="movePlayer1Up" value="w">
<br>Move Player 1 Down:
<br>
<input type="text" name="movePlayer1Down" value="s">
<br>Move Player 2 Up:
<br>
<input type="text" name="movePlayer2Up" value="UpArrow">
<br>Move Player 2 Down:
<br>
<input type="text" name="movePlayer2Down" value="DownArrow">
<br>Save Settings and start game:
<br>
<input type="button" name="Start" value="Start" onClick="playGame(this.form)">
<br>
</form>
</body>
</html>
Above is the code that I have so far.
The part in question is the bottom part with the form and the part near the top where I am defining the variables for the settings.
I was making a pong game and it was working as expected until I tried to add a <form> so the player could customise the settings and controls.
I then set the variables I had used before to the values from this form. The problem was that when I when I added in the "player width" and "player height" variables. The game glitched out. Eg. The ball would bounce early, a paddle was missing etc.
Any ideas why this would occur when the data entered into the form was the same as the constants I had had before which worked perfectly fine.
You are reading the player width and player height in as text. You need to convert to integers. Do the same for player2.
var player1 = {
x: null,
y: null,
score: null,
width: parseInt(playerWidth),
height: parseInt(playerHeight),
Related
Here's my code:
<!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>Johnny's Potential Homepage</title>
<style type="text/css">
#font-face {
font-family: Abel Regular;
src: url("fonts/Abel-Regular.ttf");
}
body {
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.destinationX = x;
this.destinationY = y;
this.originalRadius = radius;
this.radius = radius/2;
this.contentAlpha = 0;
this.displayDelay = 50;
this.displayDelayTicker = 0;
}
update() {
var offset = Math.sqrt(Math.sqrt(Math.pow(this.x-mouseX, 2)+(Math.pow(this.y-mouseY, 2))));
var angle = -Math.atan2(this.x-mouseX, this.y-mouseY) - Math.PI/2;
this.destinationX = canvas.width / 2 + offset * Math.cos(angle);
this.destinationY = canvas.height / 2 + offset * Math.sin(angle);
this.fixCollisions();
this.x += (this.destinationX - this.x) / 10;
this.y += (this.destinationY - this.y) / 10;
this.radius += (this.originalRadius - this.radius) / 10;
if (this.displayDelayTicker >= this.displayDelay) {
this.contentAlpha += (1 - this.contentAlpha) / 10;
}
this.displayDelayTicker = Math.min(this.displayDelay, this.displayDelayTicker+1);
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.fillStyle = "#000";
ctx.filter = "blur(120px)";
ctx.fill();
ctx.filter = "blur(0px)";
ctx.fillStyle = "rgba(0, 0, 0, 0.8)";
ctx.fill();
}
fixCollisions() {
for (var i = 0; i < circles.length; i++) {
if (circles[i] != this) {
var angle = getAngle([this.x, this.y], [circles[i].x, circles[i].y]);
var dist = ((this.radius + circles[i].radius)/2 + padding);
// Distribute
this.destinationX += Math.cos(-angle) * dist;
this.destinationY += Math.sin(-angle) * dist;
}
}
}
}
class Centerpiece extends Circle {
constructor(x, y, radius) {
super(x, y, radius);
this.time = 0;
this.readTime = "";
this.readSeconds = "";
}
update() {
super.update();
var date = new Date();
var destTime = date.getHours()*3600 + date.getMinutes()*60 + date.getSeconds();
if (this.displayDelayTicker >= this.displayDelay) {
this.time += (destTime - this.time) / 10;
}
var hours = Math.floor(this.time / 3600);
if (hours > 12) {
hours -= 12;
}
var minutes = (this.time/60) % 60;
minutes = Math.floor(minutes);
if (minutes < 10) {
minutes = "0" + minutes;
}
var seconds = (this.time) % 60;
seconds = Math.floor(seconds);
if (seconds < 10) {
seconds = "0" + seconds;
}
this.readTime = hours + ":" + minutes;
this.readSeconds = seconds;
}
draw() {
super.draw();
ctx.font = "14px Abel Regular";
var secondsWidth = ctx.measureText(this.readSeconds).width;
ctx.font = "21px Abel Regular";
var timeWidth = ctx.measureText(this.readTime).width;
ctx.textAlign = "center";
ctx.fillStyle = "rgba(255, 255, 255, " + this.contentAlpha + ")";
ctx.fillText(this.readTime, this.x - secondsWidth/2 -1, this.y);
ctx.font = "14px Abel Regular";
ctx.fillText(this.readSeconds, this.x + timeWidth/2 + 1, this.y);
}
}
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var circles = [];
var mouseX = canvas.width/2;
var mouseY = canvas.height/2;
var scale = 1.0;
var scrollAmount = 0;
var padding = Math.sqrt(getDistance([0, 0], [canvas.width/2, canvas.height/2]));
circles.push(new Centerpiece(canvas.width/2, canvas.height/2, 120));
circles.push(new Centerpiece(canvas.width/2, canvas.height/2, 100));
circles.push(new Centerpiece(canvas.width/2, canvas.height/2, 80));
circles.push(new Centerpiece(canvas.width/2, canvas.height/2, 90));
window.onresize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var padding = Math.sqrt(getDistance([0, 0], [canvas.width/2, canvas.height/2])) + 10;
}
window.onmousemove = function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
window.onwheel = function(e) {
scrollAmount -= Math.min(Math.max(-0.5, e.deltaY), 0.5);
scale = (Math.log10(Math.min(2, Math.max(0.5, scrollAmount + 1)))) + 1;
console.log(scrollAmount + " " + scale);
}
function getDistance(a, b) {
return (Math.sqrt((b[0]-a[0])*(b[0]-a[0])-(b[1]-a[1])*(b[1]-a[1])));
}
function getAngle(a, b) {
return Math.atan2(b[1] - a[1], b[0] - a[0]);
}
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < circles.length; i++) {
circles[i].update();
}
for (var i = 0; i < circles.length; i++) {
circles[i].draw();
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
My goal is to have the circles "glob" together in the middle, yet not collide. Take a look at the fixCollisions() function and see if there's a way to update things so the circles spread evenly across the x and y axis.
Also, I'm not sure why it bugs out at the beginning.
I think this does what you need, if I understood correctly. I commented out some lines and changed some others. I removed the mouse following part because I did not get to fix that and it causes a problem by resetting the position of the blobs every time it updates.
Then I changed the way the blobs are made to be attracted to each other but not allowing them to overlap.
I also simplified the way the sines and cosines are calculated. You don't actually need to first find the angle and the take the cosine and sine of the angle since you already have these when dividing the x and y displacements by the distance. That is in actual fact dividing the opposite and the adjacent sides by the hypotenuse, which is actually the definition of a sine and cosine.
<!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>Johnny's Potential Homepage</title>
<style type="text/css">
#font-face {
font-family: Abel Regular;
src: url("fonts/Abel-Regular.ttf");
}
body {
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.destinationX = x;
this.destinationY = y;
this.originalRadius = radius;
this.radius = radius/2;
this.contentAlpha = 0;
this.displayDelay = 50;
this.displayDelayTicker = 0;
}
update() {
var offset = Math.sqrt(Math.sqrt(Math.pow(this.x-mouseX, 2)+(Math.pow(this.y-mouseY, 2))));
var angle = -Math.atan2(this.x-mouseX, this.y-mouseY) - Math.PI/2;
//this.destinationX = canvas.width / 2 + offset * Math.cos(angle);
//this.destinationY = canvas.height / 2 + offset * Math.sin(angle);
this.fixCollisions();
this.x += (this.destinationX - this.x) / 10;
this.y += (this.destinationY - this.y) / 10;
// removed this.radius += (this.originalRadius - this.radius) / 10;
// changed
this.x += Math.min( 1 * ( canvas.width / 2 - this.x ),1 );
this.y += Math.min( 1 * ( canvas.height / 2 - this.y ),1 );
if (this.displayDelayTicker >= this.displayDelay) {
this.contentAlpha += (1 - this.contentAlpha) / 10;
}
this.displayDelayTicker = Math.min(this.displayDelay, this.displayDelayTicker+1);
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.fillStyle = "#000";
ctx.filter = "blur(120px)";
ctx.fill();
ctx.filter = "blur(0px)";
ctx.fillStyle = "rgba(0, 0, 0, 0.8)";
ctx.fill();
}
fixCollisions() {
for (var i = 0; i < circles.length; i++)
{
if (circles[i] != this) {
//var angle = getAngle([this.x, this.y], [circles[i].x, circles[i].y]);
//var dist = ((this.radius + circles[i].radius)/2 + padding);
var minDist = ((this.radius + circles[i].radius));
var dist = Math.sqrt( (this.x-circles[i].x)*(this.x-circles[i].x) + (this.y-circles[i].y)*(this.y-circles[i].y) )
// Distribute
if ( dist < minDist) // overlapping so push away
{
this.destinationX += 100 * (( this.x - circles[i].x) / minDist ) / ( dist + 1 );
this.destinationY += 100 * (( this.y - circles[i].y) / minDist ) / ( dist + 1 );
}
if ( dist > minDist) // overlapping so push away
{
this.destinationX += -0.001 * (( this.x - circles[i].x) / minDist ) * dist;
this.destinationY += -0.001 * (( this.y - circles[i].y) / minDist ) * dist;
}
}
}
}
}
class Centerpiece extends Circle {
constructor(x, y, radius) {
super(x, y, radius);
this.time = 0;
this.readTime = "";
this.readSeconds = "";
}
update() {
super.update();
var date = new Date();
var destTime = date.getHours()*3600 + date.getMinutes()*60 + date.getSeconds();
if (this.displayDelayTicker >= this.displayDelay) {
this.time += (destTime - this.time) / 10;
}
var hours = Math.floor(this.time / 3600);
if (hours > 12) {
hours -= 12;
}
var minutes = (this.time/60) % 60;
minutes = Math.floor(minutes);
if (minutes < 10) {
minutes = "0" + minutes;
}
var seconds = (this.time) % 60;
seconds = Math.floor(seconds);
if (seconds < 10) {
seconds = "0" + seconds;
}
this.readTime = hours + ":" + minutes;
this.readSeconds = seconds;
}
draw() {
super.draw();
ctx.font = "14px Abel Regular";
var secondsWidth = ctx.measureText(this.readSeconds).width;
ctx.font = "21px Abel Regular";
var timeWidth = ctx.measureText(this.readTime).width;
ctx.textAlign = "center";
ctx.fillStyle = "rgba(255, 255, 255, " + this.contentAlpha + ")";
ctx.fillText(this.readTime, this.x - secondsWidth/2 -1, this.y);
ctx.font = "14px Abel Regular";
ctx.fillText(this.readSeconds, this.x + timeWidth/2 + 1, this.y);
}
}
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var circles = [];
var mouseX = canvas.width/2;
var mouseY = canvas.height/2;
var scale = 1.0;
var scrollAmount = 0;
var padding = Math.sqrt(getDistance([0, 0], [canvas.width/2, canvas.height/2]));
circles.push(new Centerpiece(0.27 * canvas.width, 0.67 * canvas.height/2, 120));
circles.push(new Centerpiece(0.98 * canvas.width, 0.23 * canvas.height/2, 100));
circles.push(new Centerpiece(0.46 * canvas.width, 0.15 * canvas.height/2, 80));
circles.push(new Centerpiece(0.37 * canvas.width, 0.29 * canvas.height/2, 90));
window.onresize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var padding = Math.sqrt(getDistance([0, 0], [canvas.width/2, canvas.height/2])) + 10;
}
window.onmousemove = function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
window.onwheel = function(e) {
scrollAmount -= Math.min(Math.max(-0.5, e.deltaY), 0.5);
scale = (Math.log10(Math.min(2, Math.max(0.5, scrollAmount + 1)))) + 1;
console.log(scrollAmount + " " + scale);
}
function getDistance(a, b) {
return (Math.sqrt((b[0]-a[0])*(b[0]-a[0])-(b[1]-a[1])*(b[1]-a[1])));
}
function getAngle(a, b) {
return Math.atan2(b[1] - a[1], b[0] - a[0]);
}
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < circles.length; i++) {
circles[i].update();
}
for (var i = 0; i < circles.length; i++) {
circles[i].draw();
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
Im new to this area and hope some off you can help me.
I am super inspired be this site and the particle animation / function they have http://www.giantstepsmedias.com/
I found this one that are close to the inspiration. But i can't figure out how to change it to an images instead of the value in the input field.
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {x:0,y:0},
radius = 1;
var colors = ["rgba(255,255,255,1)","rgba(255,255,255,.5)", "rgba(255,255,255,.25)","rgba(255,255,255,.1)"];
var copy = document.querySelector("#copy");
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x,y){
this.x = Math.random()*ww;
this.y = Math.random()*wh;
this.dest = {
x : x,
y: y
};
this.r = Math.random()*5 + 2;
this.vx = (Math.random()-0.5)*20;
this.vy = (Math.random()-0.5)*20;
this.accX = 0;
this.accY = 0;
this.friction = Math.random()*0.05 + 0.94;
this.color = colors[Math.floor(Math.random()*6)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x)/1000;
this.accY = (this.dest.y - this.y)/1000;
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt( a*a + b*b );
if(distance<(radius*70)){
this.accX = (this.x - mouse.x)/100;
this.accY = (this.y - mouse.y)/100;
this.vx += this.accX;
this.vy += this.accY;
}
}
function onMouseMove(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function onTouchMove(e){
if(e.touches.length > 0 ){
mouse.x = e.touches[0].clientX;
mouse.y = e.touches[0].clientY;
}
}
function onTouchEnd(e){
mouse.x = -9999;
mouse.y = -9999;
}
function initScene(){
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "bold "+(ww/10)+"px sans-serif";
ctx.textAlign = "center";
ctx.fillText(copy.value, ww/2, wh/2);
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for(var i=0;i<ww;i+=Math.round(ww/150)){
for(var j=0;j<wh;j+=Math.round(ww/150)){
if(data[ ((i + j*ww)*4) + 3] > 150){
particles.push(new Particle(i,j));
}
}
}
amount = particles.length;
}
function onMouseClick(){
radius++;
if(radius ===5){
radius = 0;
}
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
copy.addEventListener("keyup", initScene);
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("touchmove", onTouchMove);
window.addEventListener("click", onMouseClick);
window.addEventListener("touchend", onTouchEnd);
initScene();
requestAnimationFrame(render);
canvas{
background: black;
width: 100vw;
height: 100vh;
}
<canvas id="scene"></canvas>
<input id="copy" type="text" value="Hello Codepen ♥" />
The animation is based on whatever has been rendered to the canvas.
In your code that is
ctx.font = "bold "+(ww/10)+"px sans-serif";
ctx.textAlign = "center";
ctx.fillText(copy.value, ww/2, wh/2);
instead, change this to render an image:
const img = document.getElementById('img');
ctx.drawImage(img, ww/2, wh/2);
you might like to adjust the positions for .drawImage: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
Using HTML:
<canvas id="scene"></canvas>
<div style="display:none;">
<img id="img"
src="http://www.giantstepsmedias.com/img/logos/giant_steps_small.png">
</div>
However, rendering an image from a different server to your ctx gives The canvas has been tainted by cross-origin data so I can't give you a working snippet.
Use an image that is on the same server as the page or, as suggested, use a data: url:
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {
x: 0,
y: 0
},
radius = 1;
var colors = ["rgba(255,255,255,1)", "rgba(255,255,255,.5)", "rgba(255,255,255,.25)", "rgba(255,255,255,.1)"];
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x, y) {
this.x = Math.random() * ww;
this.y = Math.random() * wh;
this.dest = {
x: x,
y: y
};
this.r = Math.random() * 5 + 2;
this.vx = (Math.random() - 0.5) * 20;
this.vy = (Math.random() - 0.5) * 20;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.05 + 0.94;
this.color = colors[Math.floor(Math.random() * 6)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x) / 1000;
this.accY = (this.dest.y - this.y) / 1000;
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt(a * a + b * b);
if (distance < (radius * 70)) {
this.accX = (this.x - mouse.x) / 100;
this.accY = (this.y - mouse.y) / 100;
this.vx += this.accX;
this.vy += this.accY;
}
}
function onMouseMove(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function onTouchMove(e) {
if (e.touches.length > 0) {
mouse.x = e.touches[0].clientX;
mouse.y = e.touches[0].clientY;
}
}
function onTouchEnd(e) {
mouse.x = -9999;
mouse.y = -9999;
}
function initScene() {
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.font = "bold "+(ww/10)+"px sans-serif";
//ctx.textAlign = "center";
//ctx.fillText(copy.value, ww/2, wh/2);
const img = document.getElementById('img');
ctx.drawImage(img, ww / 2 - 75, (wh / 2) - 75, 150, 150);
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for (var i = 0; i < ww; i += Math.round(ww / 150)) {
for (var j = 0; j < wh; j += Math.round(ww / 150)) {
if (data[((i + j * ww) * 4) + 3] > 150) {
particles.push(new Particle(i, j));
}
}
}
amount = particles.length;
}
function onMouseClick() {
radius++;
if (radius === 5) {
radius = 0;
}
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("touchmove", onTouchMove);
window.addEventListener("click", onMouseClick);
window.addEventListener("touchend", onTouchEnd);
initScene();
requestAnimationFrame(render);
canvas {
background: black;
width: 100vw;
height: 100vh;
}
<canvas id="scene"></canvas>
<div style="display:none;">
<img id="img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAsCAYAAAAJpsrIAAAC9UlEQVR42syZSWgUQRSGezJJ0IhLwIDLRQkumEMOihdFPOghcd9QEEREiIokHkQRISAKRsUdEUxAL2pGxV08iQt40QgexAUNiBgFSQY0EjEzk/J/8kqHobvrRat76sE3E7prar55vdTrl4RS6oXneaNBzvsbSdAPjoATYMCzFw3gAMj6zEvf2w2mlOJlPBgVMAmJTQY7Qa8lsQowMmR/iX7JhAxKgM0gBSZaEjNlP/PHThB14BaY48UUJYMYW8NyG1wToxgB2sA+MNQlMX3e7QZnwTiXxHSsBjfBTNfEKKaDa2BF3GIK/DSMocN5ke91ZXGKHQPthnEk1ALO8CoSuRjtfwvWg1bBfDTuMpgaxzk2nA8nrXHbQZ9h/FxwG8yPWkzlvR/mrHwyfKaaM7clzquSvnAZeG4YRwv1KXAcDItCrN9n2xOwiA+ZKRr5qtVFQLktsTVgks/2j7zvqKBioB9xndfbPlHKUCh+UeZ4DWYDL4BG0CuYpxPcAwMhY8hHLEbRAzaGyNWBD+r/Y9Biin/pQVARIFcLOoohpuMSGBsgNwakiiWmODMzAuTKwH6QKYYYRRdYFXLeNYCvxRCjyIJmzpKf3Dy+Gq2K0cmeFk7YBqoC5GrAA9sZo2zsEU76kCX85CrBOc6wFbFtPHET+C6QewfqA+SSoFUiJlmS9NMQLcZrhZVFe0BlQW2IDltrZTbv7xtgMXgqqOGosjjp0w4YYkussOZ/BpaAq4LPbgXnwYQoyp6Ez7bPXFkcKsioXywAd/LaCyrqxzdqfuzgeuubYew0cAXUgx+SyUstPNCcBu/5fKoOGVcFLvDYHPfCInvg1XGXL4rHgnK71iRlU4ziJculXGgRFEYarAN7DQ3B2MX0w0sz32DTLonpoD7aSvDGNTGK+3wfe+SaGEUnWM4ZdEqMogdsArsEba1YxXRl0cK9j26JmKnZlrQsSCXRUvAqpNf2e0nq4vTmfBbvcsE6+C9BK8RCbi/Myju8+l823i8BBgAb0AQfHTBwWAAAAABJRU5ErkJggg=="
alt="" />
</div>
This is a code from codepen. I am trying to work on this one. This code works on chrome but does not work in firefox or edge. I tried to solve the issue but could not fix it. Is the problem with requestAnimationFrame or something else? Can anyone please help? Here is the codepen link: https://codepen.io/iremlopsum/pen/MKNaxd
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {
x: 0,
y: 0
},
radius = 0.7; //Init radius of the force field
var colors = ["rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)"];
var colorsTwo = ["rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)"];
var copy = "Mighty Byte"; // Text to display
var initSize = Math.floor(Math.random() * .6) + 1 ;
var hoverSize = initSize + .7;
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x, y) {
this.x = Math.random() * ww;
this.y = Math.random() * wh;
this.dest = {
x: x,
y: y
};
//this.r = Math.random() * 1; // the size of bubbles
this.vx = (Math.random() - 0.5) * 2;
this.vy = (Math.random() - 0.5) * 2;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.015 + 0.94; // force of bounce, just try to change 0.015 to 0.5
//this.color = colors[Math.floor(Math.random() * 10)];
//this.colorTwo = colorsTwo[Math.floor(Math.random() * 10)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x) / 200; //acceleration for X
this.accY = (this.dest.y - this.y) / 200; //acceleration for Y
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt(a * a + b * b);
if (distance < (radius * 70)) {
this.accX = (this.x - mouse.x) / 20; //acceleration on mouseover X, smaller faster
this.accY = (this.y - mouse.y) / 20; //acceleration on mouseover Y, smaller faster
this.vx += this.accX;
this.vy += this.accY;
//ctx.fillStyle = this.colorTwo;
}
if (distance < (radius * 70)) {
this.colorTwo = colorsTwo[Math.floor(Math.random() * 10)];
ctx.fillStyle = this.colorTwo;
this.r = hoverSize; // the size of bubbles
}
if (distance > (radius * 70)) {
this.colorOne = colors[Math.floor(Math.random() * 10)];
ctx.fillStyle = this.colorOne;
this.r = initSize
}
}
function onMouseMove(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function initScene() {
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "bold " + (ww / 10) + "px sans-serif"; // Size of the text
ctx.textAlign = "center";
ctx.fillText(copy, ww / 2, wh / 2); //Centering
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for (var i = 0; i < ww; i += Math.round(ww / 400)) { //400 here represents the amount of particles
for (var j = 0; j < wh; j += Math.round(ww / 400)) {
if (data[((i + j * ww) * 4) + 3] > 250) {
particles.push(new Particle(i, j));
}
}
}
amount = particles.length;
}
function onMouseClick() {
radius = 4; //onclick expand radius
}
function offMouseClick() {
radius = 0.5; //offClick init radius
}
function delayedInitRadius() {
setTimeout(offMouseClick, 500); //delay for offClick init radius
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mousedown", onMouseClick);
window.addEventListener("mouseup", delayedInitRadius);
initScene();
requestAnimationFrame(render);
I am trying to make a webpage to store all my games on i just started and i've been trying to make a button to load my pong game but when I press the button nothing happens here's my code
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Title</title>
<meta charset="UTF-8">
<style>
canvas {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<center>
<h1>Games</h1>
button code
<input id="Pong" type="button" value="Pong" onclick="go();" />
pong code
<script>
function go(){
var WIDTH = 700, HEIGHT = 600, pi = Math.PI;
var UpArrow = 38, DownArrow = 40;
var canvas, ctx, keystate;
var player, ai, ball, score;
player = {
x: null,
y: null,
width: 20,
height: 100,
update: function(){
if(keystate[UpArrow]) this.y -= 7;
if(keystate[DownArrow]) this.y += 7;
},
draw: function(){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
ai = {
x: null,
y: null,
width: 20,
height: 100,
update: function(){
var desty = ball.y - (this.height - ball.side)*0.5;
this.y += (desty - this.y) * 0.1;
},
draw: function(){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
ball = {
x: null,
y: null,
vel: null,
side: 20,
speed: 9,
serve: function(side){
var r = Math.random();
this.x = side===1 ? player.x : ai.x - this.side;
this.y = (HEIGHT - this.side)*r;
score.count += 1;
var phi = 0.1*pi*(1 - 2*r);
this.vel = {
x: side*this.speed*Math.cos(phi),
y: this.speed*Math.sin(phi)
};
score = {
x: null,
y: null,
count: 0,
width: 10,
height: 10,
update: function(){
Console.log(this.count);
},
draw: function(){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
},
update: function(){
this.x += this.vel.x;
this.y += this.vel.y;
if(0 > this.y || this.y+this.side > HEIGHT){
var offset = this.vel.y < 0 ? 0 - this.y : HEIGHT - (this.y+this.side);
this.y += 2*offset;
this.vel.y *= -1;
}
var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh){
return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
};
var pdle = this.vel.x < 0 ? player : ai;
if(AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height, this.x, this.y, this.side, this.side)){
this.x = pdle===player ? player.x+player.width : ai.x - this.side;
var n = (this.y + this.side - pdle.y)/(pdle.height+this.side);
var phi = 0.25*pi*(2*n - 1);
var smash = Math.abs(phi) > 0.2*pi ? 1.5 : 1;
this.vel.x = smash*(pdle === player ? 1 : -1)*this.speed*Math.cos(phi);
this.vel.y = smash*this.speed*Math.sin(phi);
}
if(0 > this.x+this.side || this.x > WIDTH){
this.serve(pdle === player ? 1 : -1);
}
},
draw: function(){
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
function main(){
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init();
var loop = function(){
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init(){
player.x = player.width;
player.y = (HEIGHT - player.height)/2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height)/2;
ball.serve(1);
}
function update(){
ball.update();
player.update();
ai.update();
}
function draw(){
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
ball.draw();
player.draw();
ai.draw();
var w = 4;
var x = (WIDTH - w) * 0.5;
var y = 0;
var step = HEIGHT/15;
while (y < HEIGHT){
ctx.fillRect(x, y + step * 0.25, w, step * 0.5);
y += step;
}
ctx.restore();
}
main();
}
</script>
end of pong code
</center>
</body>
</html>
I merely took #Xufox's solutions and wrote them out. Also serperated the JS, CSS, and HTML. Enjoy
function go(){
score = {
x: null,
y: null,
count: 0,
width: 10,
height: 10,
update: function(){
console.log(this.count);
},
draw: function(){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
var WIDTH = 700, HEIGHT = 600, pi = Math.PI;
var UpArrow = 38, DownArrow = 40;
var canvas, ctx, keystate;
var player, ai, ball, score;
player = {
x: null,
y: null,
width: 20,
height: 100,
update: function(){
if(keystate[UpArrow]) this.y -= 7;
if(keystate[DownArrow]) this.y += 7;
},
draw: function(){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
ai = {
x: null,
y: null,
width: 20,
height: 100,
update: function(){
var desty = ball.y - (this.height - ball.side)*0.5;
this.y += (desty - this.y) * 0.1;
},
draw: function(){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
ball = {
x: null,
y: null,
vel: null,
side: 20,
speed: 9,
serve: function(side){
var r = Math.random();
this.x = side===1 ? player.x : ai.x - this.side;
this.y = (HEIGHT - this.side)*r;
score.count += 1;
var phi = 0.1*pi*(1 - 2*r);
this.vel = {
x: side*this.speed*Math.cos(phi),
y: this.speed*Math.sin(phi)
};
},
update: function(){
this.x += this.vel.x;
this.y += this.vel.y;
if(0 > this.y || this.y+this.side > HEIGHT){
var offset = this.vel.y < 0 ? 0 - this.y : HEIGHT - (this.y+this.side);
this.y += 2*offset;
this.vel.y *= -1;
}
var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh){
return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
};
var pdle = this.vel.x < 0 ? player : ai;
if(AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height, this.x, this.y, this.side, this.side)){
this.x = pdle===player ? player.x+player.width : ai.x - this.side;
var n = (this.y + this.side - pdle.y)/(pdle.height+this.side);
var phi = 0.25*pi*(2*n - 1);
var smash = Math.abs(phi) > 0.2*pi ? 1.5 : 1;
this.vel.x = smash*(pdle === player ? 1 : -1)*this.speed*Math.cos(phi);
this.vel.y = smash*this.speed*Math.sin(phi);
}
if(0 > this.x+this.side || this.x > WIDTH){
this.serve(pdle === player ? 1 : -1);
}
},
draw: function(){
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
function main(){
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init();
var loop = function(){
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init(){
player.x = player.width;
player.y = (HEIGHT - player.height)/2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height)/2;
ball.serve(1);
}
function update(){
ball.update();
player.update();
ai.update();
}
function draw(){
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
ball.draw();
player.draw();
ai.draw();
var w = 4;
var x = (WIDTH - w) * 0.5;
var y = 0;
var step = HEIGHT/15;
while (y < HEIGHT){
ctx.fillRect(x, y + step * 0.25, w, step * 0.5);
y += step;
}
ctx.restore();
}
main();
}
canvas {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Title</title>
<meta charset="UTF-8">
</head>
<body>
<center>
<h1>Games</h1>
<input id="Pong" type="button" value="Pong" onclick="go();" />
</center>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
Recently, i made a game on codepen.io called flappy bird an it was working fine there but when i tried to show it on my website it doesn't show up anything.
Can someone tell what's missing or what is the problem in my code.
here is the code ( sorry it's too long , i know but i need help ):
<html>
<head>
<style type="text/css">
#stage {
display:block;
border:solid 1px #000;
margin:auto;
}
body{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background:#333;
}
</style>
<script type="text/javascript">
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(cb){
return setTimeout(cb, 1000/60);
};
})()
var can = document.getElementById("stage"),
ctx = can.getContext('2d'),
wid = can.width,
hei = can.height,
player, floor, pillars, gravity, thrust, running,
rainbows, colider, score, gPat, pPat, trans, termVel, pillGap,
pillWid, pillSpace, speed, stars, high,
sprite = document.createElement("img");
sprite.src = "http://www.cutmypic.com/uploads/title85083782.png";
//sprite.src = "http://i.stack.imgur.com/Vy3qB.gif";
sprite.onload = function(){
sprite.style.height = 0;
loop();
};
sprite.width = 34;
sprite.height = 21;
document.body.appendChild(sprite);
function init() {
high = localStorage.getItem("high") || 0;
player = {
x: 1 / 3 * wid,
y: 2 / 5 * hei,
r: 13,
v: 0
};
speed = 2.5;
floor = 4 / 5 * hei;
pillars = [];
rainbows = [];
stars = [];
gravity = .30;
thrust = gravity * -21;
termVel = -thrust + 2;
running = false;
colider = false;
score = 0;
trans = 0;
pillGap = 135;
pillWid = 55;
pillSpace = pillWid*3;
pPat = ctx.createPattern((function(){
var can = document.createElement("canvas"),
ctx = can.getContext("2d");
can.width = 60;
can.height = 60;
["green", "green", "green",
"#3b5998", "green", "#3b5998"].forEach(function(color, i){
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(i*10, 0);
ctx.lineTo(i*10+10, 0);
ctx.lineTo(0, i*10+10);
ctx.lineTo(0, i*10);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(i*10, 60);
ctx.lineTo(i*10+10, 60);
ctx.lineTo(60, i*10+10);
ctx.lineTo(60, i*10);
ctx.closePath();
ctx.fill();
});
return can;
})(), "repeat");
gPat = ctx.createPattern((function(){
var can = document.createElement("canvas"),
ctx = can.getContext("2d");
can.width = 32;
can.height = 32;
ctx.save();
ctx.translate(16,16);
ctx.rotate(Math.PI/4);
ctx.fillStyle = "#79CDCD";
ctx.fillRect(-64,-64,128,128);
ctx.fillStyle = "#528B8B";
ctx.fillRect(-8,-64,8,128);
ctx.fillRect(14.5,-64,8,128);
ctx.restore();
return can;
})(), "repeat");
}
function render() {
trans -= speed;
rainbows = rainbows.filter(function(r){
r.x -= speed;
return r.x > -speed;
});
if (trans % speed === 0){
rainbows.push({x:player.x-10, y:player.y - (trans%50/25|0)*2 - 1});
}
stars = stars.filter(function(s){
trans % 10 || (s.r += 1);
s.x -= speed;
return s.x > -speed && s.r < 10;
});
if(trans % 20 === 0){
stars.push({
x: Math.round(Math.random()*(wid-50)+100),
y:Math.round(Math.random()*floor),
r:0
});
}
// backdrop
ctx.fillStyle = "#418bbc";
ctx.fillRect(0, 0, wid, hei);
//stars
ctx.fillStyle = "white";
stars.forEach(function (s){
ctx.fillRect(s.x, s.y - s.r-2, 2, s.r/2);
ctx.fillRect(s.x - s.r-2, s.y, s.r/2, 2);
ctx.fillRect(s.x, s.y+s.r + 2, 2, s.r/2);
ctx.fillRect(s.x+s.r + 2, s.y, s.r/2, 2);
ctx. fillRect(s.x + s.r, s.y + s.r, 2, 2);
ctx. fillRect(s.x - s.r, s.y - s.r, 2, 2);
ctx. fillRect(s.x + s.r, s.y - s.r, 2, 2);
ctx. fillRect(s.x - s.r, s.y + s.r, 2, 2);
});
//ground
ctx.fillStyle = "#2F4F4F";
ctx.fillRect(0, floor, wid, hei-floor);
ctx.save();
ctx.translate(trans, 0);
//pillars
ctx.fillStyle = pPat;
ctx.strokeStyle = "#ccc";
ctx.lineWidth = 2;
for (var i = 0; i < pillars.length; i++){
var pill = pillars[i];
ctx.fillRect(pill.x, pill.y, pill.w, pill.h);
ctx.strokeRect(pill.x, pill.y, pill.w, pill.h);
}
// stripe
ctx.fillStyle = gPat;
ctx.fillRect(-trans, floor+2, wid, 15);
ctx.restore();
//rainbowwwwws
rainbows.forEach(function(r){
["red","orange","blue","green","blue","indigo"].forEach(function(color, i){
ctx.fillStyle = color;
ctx.fillRect(r.x - speed, r.y-9 + i*3, speed+1, 3);
});
});
//player
ctx.save();
ctx.translate(player.x, player.y);
ctx.rotate(player.v*Math.PI/18);
ctx.drawImage(sprite, - 17, - 10);
ctx.restore();
ctx.fillStyle = "#97FFFF";
ctx.fillRect(0, floor, wid, 2);
ctx.fillStyle = "#2F4F4F";
ctx.fillRect(0, floor+1, wid, 1);
ctx.fillStyle = "#97FFFF";
ctx.fillRect(0, floor+17, wid, 2);
ctx.fillStyle = "#2F4F4F";
ctx.fillRect(0, floor+17, wid, 1);
//score
ctx.font = "bold 30px monospace";
var hScore = "best:" + (score > high ? score : high),
sWid = ctx.measureText(hScore).width,
sY = 50;
ctx.fillStyle = "black";
ctx.fillText(score, 12, floor + sY + 2);
ctx.fillText(hScore, wid - sWid - 10, floor + sY + 2);
ctx.fillStyle = "white";
ctx.fillText(score, 10, floor + sY);
ctx.fillText(hScore, wid - sWid - 12, floor + sY);
}
function adjust() {
if (trans%pillSpace === 0){
var h;
pillars.push({
x: -trans + wid,
y: 0,
w: pillWid,
h: (h = Math.random() * (floor - 300) + 100)
});
pillars.push({
x: -trans + wid,
y: h + pillGap,
w: pillWid,
h: floor - h - pillGap
});
}
pillars = pillars.filter(function(pill){
return -trans < pill.x + pill.w;
});
player.v += gravity;
if (player.v > termVel){
player.v = termVel;
}
player.y += player.v;
if (player.y < player.r) {
player.y = player.r;
player.v = 0;
}
for(var i = 0; i < pillars.length; i++){
var pill = pillars[i];
if (pill.x + trans < player.x + player.r &&
pill.x + pill.w + trans > player.x - player.r){
if (player.y - player.r > pill.y &&
player.y - player.r < pill.y + pill.h){
colider = true
running = false;
render();
break;
}
if (player.y + player.r < pill.y + pill.h &&
player.y + player.r > pill.y){
colider = true
running = false;
render();
break;
}
if (!pill.passed && i%2 == 1){
score++;
pill.passed = true;
}
}
}
if (player.y + player.r - player.v > floor) {
player.y = floor - player.r;
running = false;
colider = true;
render();
}
}
document.onmousedown = function () {
if (running) {
player.v = thrust;
} else if (!colider) {
running = true;
} else {
if (score > high){
localStorage.setItem("high", score);
}
init();
}
};
</script>
</head>
<body>
<canvas id="stage" width="400" height="600"></canvas>
</body>
Your calling document.getElementById('stage') before #stage exists in the DOM.
Javascript is run in the order that it is loaded into the page. So, you could either move the Javascript to the bottom of your HTML document, or us an onload event listener.
In detail, as the page loads, things at the top of the page are pulled in and parsed first. When a <script> tag is encountered, the browser automatically runs the Javascript immediately -- before it has reached the body of the page. Your CodePen was likely set to run the code after the page had loaded completely, but when you moved it all to it's own page you were now running it before load.