Else If statement never runs - javascript

So I'm trying to implement platforms for the game I'm making for a project (similar to falldown) and have created multiple arrays that have contain all the possible platforms (canvas is 360 so there is if platform[i] == 1 it draws a rect)
var canvas;
var ctx;
var isPlaying = false;
window.onload = function(){
canvas= document.getElementById("gamesCanvas");
ctx = canvas.getContext("2d");
var fps = 60;
setInterval(function(){
}, 1000/fps);
createMenu();
canvas.addEventListener('click', getClicks.bind(this), false)
//canvas.addEventListener("mousemove", getPos)
}
function initialise(){
isPlaying = true;
ctx.clearRect(0, 0, canvas.width, canvas.height);
createRect(0,0, canvas.width, canvas.height, 'black');
createPlatforms();
}
function createPlatforms(){
x = randint(1,2);
console.log(x)
var i;
var pos = -60;
var platform1 = [0,1,1,1,1,1];
var platform2 = [1,0,1,1,1,1];
var platform3 = [1,1,0,1,1,1];
var platform4 = [1,1,1,0,1,1];
var platform5 = [1,1,1,1,0,1];
var platform6 = [1,1,1,1,1,0];
if(x==1){
for (i=0; i<platform1.length; ++i) {
var pos = (pos+60);
if(platform1[i] == 1){
createRect(pos, 60, 60,5, 'white');
}
}
}
else if(x==2){
for (i=0; i<platform2.length; ++i){
var pos = (pos+60);
if (platform2[i] ==2){
createRect(pos,60,75,5,'white');
}
}
}
}
function randint(min, max) {
return ~~(Math.random() * (max - min + 1) + min);
}
function background(color) {
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function createMenu(){
background("black");
if (!isPlaying) {
ctx.font = "60px monospace";
ctx.fillStyle = "white";
ctx.fillText("FallDown", 40, 130);
ctx.font = "34px Arial";
ctx.fillStyle = "white";
ctx.fillText("PLAY", 130, 260);
ctx.font = "34px Arial";
ctx.fillStyle = "white";
ctx.fillText("LEADERBOARD", 50, 340);
ctx.font = "34px Arial";
ctx.fillStyle = "white";
ctx.fillText("SETTINGS", 90, 420);
}
}
function createRect(leftX, topY, width, height, color){
ctx.fillStyle = color;
ctx.fillRect(leftX, topY, width, height);
}
function getClicks(evt) {
var x = evt.offsetX;
var y = evt.offsetY;
if ((x > 110 && x < 240) && (y > 220 && y < 275) && !isPlaying) {
initialise()
}
}
<html>
<head>
<title>Falldown</title>
</head>
<body>
<canvas id="gamesCanvas" width="360" height="640"></canvas>
<!--script src="test.js"></script-->
</body>
</html>
However, if x>1 (so basically an else if statement is required to run) it doesn't draw anything.
I was testing to see whether it is something that I could fix, however, all I managed to realise that if the if statement has got the contents of the else if statement than it will draw the rects in the right position so in this case (platform2) would be drawn.
I've managed to narrow down the problem but I'm not sure how to fix it. I have experience with python but have never experienced anything like this
Just letting you know that I can't just use the else statement as I have to implement 6 platforms and if I were to use just if and else than that would mean I could only draw 2 of the 6 platforms

Your initial problem wasn't with the if / else.. but the if inside..
But with -> if (platform2[i] ==2){ this wanted to be if (platform2[i] == 1){
But saying all this, your createPlatforms was only creating a single platform. It didn't really need any If/else or arrays.
Below I've modified createPlatforms, using just two for loops.
var canvas;
var ctx;
var isPlaying = false;
window.onload = function(){
canvas= document.getElementById("gamesCanvas");
ctx = canvas.getContext("2d");
var fps = 60;
setInterval(function(){
}, 1000/fps);
createMenu();
canvas.addEventListener('click', getClicks.bind(this), false)
//canvas.addEventListener("mousemove", getPos)
}
function initialise(){
isPlaying = true;
ctx.clearRect(0, 0, canvas.width, canvas.height);
createRect(0,0, canvas.width, canvas.height, 'black');
createPlatforms();
}
function createPlatforms(){
for (var y = 0; y < 8; y ++) {
var x = randint(0, 5), pos = 0;
for (var i = 0; i < 6; i ++) {
if (i !== x) {
createRect(pos, 60 + y*60 ,75,5,'white');
}
pos += 60;
}
}
}
function randint(min, max) {
return ~~(Math.random() * (max - min + 1) + min);
}
function background(color) {
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function createMenu(){
background("black");
if (!isPlaying) {
ctx.font = "60px monospace";
ctx.fillStyle = "white";
ctx.fillText("FallDown", 40, 130);
ctx.font = "34px Arial";
ctx.fillStyle = "white";
ctx.fillText("PLAY", 130, 260);
ctx.font = "34px Arial";
ctx.fillStyle = "white";
ctx.fillText("LEADERBOARD", 50, 340);
ctx.font = "34px Arial";
ctx.fillStyle = "white";
ctx.fillText("SETTINGS", 90, 420);
}
}
function createRect(leftX, topY, width, height, color){
ctx.fillStyle = color;
ctx.fillRect(leftX, topY, width, height);
}
function getClicks(evt) {
var x = evt.offsetX;
var y = evt.offsetY;
if ((x > 110 && x < 240) && (y > 220 && y < 275) && !isPlaying) {
initialise()
}
}
<html>
<head>
<title>Falldown</title>
</head>
<body>
<canvas id="gamesCanvas" width="360" height="640"></canvas>
<!--script src="test.js"></script-->
</body>
</html>

You can use a switch statement in javascript to handle lots of cases.
Example:
switch(x){
case 1:
//logic here
break;
case 2:
// and so on
break:
default:
break;
}
You can add as many cases as you would like. This will eliminate the need to use if else.
Hope this helps!

Related

Change color inside circle

I want to change color inside circle example:(two color) from red to blue and blue to red.
I tried this using if else but it didn't work for me.
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.width = window_width;
canvas.height = window_height;
let hit_counter = 0;
// object is created using class
class Circle {
constructor(xpos, ypos, radius, speed, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.speed = speed;
this.dx = 1 * this.speed;
this.dy = 1 * this.speed;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text = hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
hit_counter++;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
hit_counter++;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
hit_counter++;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
hit_counter++;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 3, 'Black', hit_counter);
let updateCircle = function() {
requestAnimationFrame(updateCircle);
my_circle.update();
}
updateCircle();
//for color
function changeColor(event) {
var coloorr = event.value;
canvas.style.background = coloorr;
}
// I tried it in bllk function but it didn't work for me.
function bllk() {
canvas.style.background = "black";
context.fillStyle = "blue";
// I tried it in bllk function but it didn't work for me.
// setInterval(() => {
// if(context.fillStyle=="blue"){
// context.fillStyle=red;
// context.fill();
// }else if(context.fillStyle=="red"){
// context.fillStyle=blue;
// context.fill();
// }else if(context.fillStyle=="blue"){
// context.fillStyle=red;
// context.fill();
// }
// }, 1000);
}
<!-- On clicking button Hi How to apply two color one by one to the numbers inside the circle ? I tried it in bllk function but it didn't work for me. -->
<button onclick="bllk()">Hi</button>
<canvas id="canvas"></canvas>
The code needed a little upgrade:
decoupling variables from each other & the global space
adding some internal attributes & methods to the circle
Now it's possible to change the background color of the canvas, the outline and text of the circle, and the background of the circle separataley.
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
// for canvas size
const window_width = window.innerWidth;
const window_height = window.innerHeight;
canvas.width = window_width;
canvas.height = window_height;
// object is created using class
class Circle {
constructor(xpos, ypos, radius, speed, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.speed = speed;
this.dx = 1 * this.speed;
this.dy = 1 * this.speed;
this.text = text;
this.color = color;
this.fillColor = "white" // added as a default value
this.hit_counter = 0
}
// outline & text in circle
drawOutline({
ctx
}) {
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.fillStyle = this.color
ctx.fillText(this.text, this.position_x, this.position_y);
ctx.textAlign = "center";
ctx.textBaseline = "middle"
ctx.font = "20px Arial";
ctx.lineWidth = 5;
ctx.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
ctx.stroke();
ctx.closePath();
}
// background of the circle
drawFill({
ctx,
color
}) {
ctx.beginPath();
ctx.fillStyle = this.fillColor
ctx.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
// drawing the circle from two pieces
draw(ctx) {
this.drawFill({
ctx
})
this.drawOutline({
ctx
})
}
// color change function
setColor({
outline,
fill
}) {
this.color = outline
this.fillColor = fill
}
update(ctx) {
this.text = this.hit_counter;
ctx.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
this.hit_counter++;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
this.hit_counter++;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
this.hit_counter++;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
this.hit_counter++;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
const my_circle = new Circle(100, 100, 50, 3, 'Black');
const updateCircle = function(ctx) {
requestAnimationFrame(() => updateCircle(ctx));
my_circle.update(ctx);
}
updateCircle(context);
// I tried it in bllk function but it didn't work for me.
function bllk1() {
canvas.style.background = "black";
my_circle.setColor({
outline: "red",
fill: "yellow"
})
}
function bllk() {
canvas.style.background = "black";
my_circle.setColor({
outline: "black",
fill: "blue"
})
setInterval(() => {
const fill = my_circle.fillColor === "blue" ? "red" : "blue"
my_circle.setColor({
outline: "black",
fill,
})
}, 1000);
}
<!-- On clicking button Hi How to apply two color one by one to the numbers inside the circle ? I tried it in bllk function but it didn't work for me. -->
<button onclick="bllk()">Hi</button>
<canvas id="canvas"></canvas>
I simplified your code to just focus on what you asked on the comments:
changing red to blue and blue to red color continuously
To focus on that specific problem we don't need the Circle moving or the collisions with the borders, in the future when you are asking a question you should do the same, provide a minimal example, remove everything else that is not specifically related to your problem.
To solve your issue we can pass a colors parameter to the draw function, that way we let it know what colors to use for the circle and the text, or anything you might want to add in the future.
See code sample below:
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
canvas.width = canvas.height = 100;
class Circle {
draw(xpos, ypos, radius, colors) {
context.beginPath();
context.arc(xpos, ypos, radius, 0, Math.PI * 2);
context.fillStyle = colors.circle;
context.fill();
context.beginPath();
context.font = "20px Arial";
context.fillStyle = colors.text;
context.fillText("0", xpos, ypos);
}
}
let my_circle = new Circle();
let colors = {text:"red", circle:"blue"};
let updateCircle = function() {
requestAnimationFrame(updateCircle);
context.clearRect(0, 0, canvas.width, canvas.height)
my_circle.draw(50, 50, 20, colors);
}
updateCircle();
setInterval(() => {
if (colors.text == "blue") {
colors = {text:"red", circle:"blue"};
} else {
colors = {text:"blue", circle:"red"};
}
}, 1000);
<canvas id="canvas"></canvas>

Canvas HTML fillText letters to not animate only shadows

Only want shadows to animate and keep the fillText from animating due to letters pixelating from getting ran over and over.
var canvas = document.getElementById('canvas')
var ctx = this.canvas.getContext('2d')
var width = canvas.width = canvas.scrollWidth
var height = canvas.height = canvas.scrollHeight
var start;
var j=0;
var makeText = function(){
j+=1
ctx.shadowColor= 'red';
ctx.shadowOffsetX = j; //animate
ctx.shadowOffsetY = j; //animate
ctx.globalAlpha=0.5;
ctx.font = "48px serif";
ctx.fillStyle = "black";
ctx.fillText('hey you', width/2, height / 2); //Only ran once so letters
//don't pixelate!
}
function animateText(timestamp){
var runtime = timestamp - start;
var progress = Math.min(runtime / 1400, 1);
makeText(progress)
if(progress < 1){
requestAnimationFrame(animateText)
}else {
return;
}
}
requestAnimationFrame(function(timestamp){
start = timestamp;
animateText(timestamp)
})
<canvas id="canvas" width=500px height=500px></canvas>
My outcome of the process would only have shadows animate and keeping letters where they are
Just draw your own shadows, here is an example:
var canvas = document.getElementById('canvas')
var ctx = this.canvas.getContext('2d')
ctx.font = "68px serif";
var base = {text: 'hey you', x: 10, y: 60 }
var inc = 2;
var j = 30;
var makeText = function() {
ctx.globalAlpha = 1;
ctx.fillStyle = "black";
ctx.fillText(base.text, base.x, base.y);
}
var makeshadow = function(offset) {
ctx.fillStyle = "red";
for (var i = 0; i < offset; i++) {
ctx.globalAlpha = 1/i;
ctx.fillText(base.text, base.x + i, base.y + i);
}
}
function animateText() {
ctx.clearRect(0, 0, 999, 999)
makeshadow(j);
makeText();
j += inc;
if (j > 35 || j < 3) inc *= -1
}
setInterval(animateText, 50)
<canvas id="canvas" width=300px height=170px></canvas>
And if you add some math in the mix you can get some cool effects:
var canvas = document.getElementById('canvas')
var ctx = this.canvas.getContext('2d')
ctx.font = "68px serif";
var base = {text: '123456', x: 30, y: 80 }
var inc = 5;
var j = 0;
var makeText = function() {
ctx.globalAlpha = 1;
ctx.fillStyle = "black";
ctx.fillText(base.text, base.x, base.y);
}
var makeshadow = function(offset) {
ctx.globalAlpha = 0.05;
ctx.fillStyle = "red";
for (var i = 0; i < offset; i++)
ctx.fillText(base.text, base.x + Math.sin(i/5)*10, base.y + Math.cos(i/5)*15);
}
function animateText() {
ctx.clearRect(0, 0, 999, 999)
makeshadow(j);
makeText();
j += inc;
if (j > 120 || j < 0) inc *= -1
}
setInterval(animateText, 50)
<canvas id="canvas" width=300px height=170px></canvas>
Your main issue (the text pixelisation) is due to you not clearing the canvas between every frames, and drawing again and again over the same position. semi-transparent pixels created by antialiasing mix up to more and more opaque pixels.
But in your situation, it seems that you actually want at-least the shadow to mix up like this.
To do it, one way would be to draw only once your normal text, and to be able to draw only the shadow, behind the current drawing.
Drawing only the shadow of a shape.
One trick to draw only the shadows of your shape is to draw your shape out of the visible viewPort, with shadowOffsets set to the inverse of this position.
var text = 'foo bar';
var ctx = canvas.getContext('2d');
var original_x = 20; // the position it would have been
ctx.font = '30px sans-serif';
var targetPosition = ctx.measureText(text).width + original_x + 2;
// default shadow settings
ctx.shadowColor = 'red';
ctx.shadowBlur = 3;
// just to show what happens
var x = 0;
anim();
function anim() {
if(++x >= targetPosition) {
x=0;
return;
}
// if we weren't to show the anim, we would use 'targetPosition'
// instead of 'x'
ctx.shadowOffsetX = x;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillText(text, -x + original_x, 30);
requestAnimationFrame(anim);
}
// restart the anim on click
onclick = function() {
if(x===0)anim();
};
<canvas id="canvas"></canvas>
Once we have this clear shadow, without our shape drawn on it, we can redraw it as we wish.
Drawing behind the current pixels
The "destination-over" compositing option does just that.
So if we put these together, we can draw behind the normal text, and only draw our shadow behind it at each frame, avoiding antialiasing mix-up.
(Note that we can also keep the clean shadow on an offscreen canvas for performances, since shadow is a really slow operation.)
var text = 'foo bar';
var ctx = canvas.getContext('2d');
ctx.font = '48px sans-serif';
var x = 20;
var y = 40;
var shadow = generateTextShadow(ctx, text, x, y, 'red', 5);
ctx.globalAlpha = 0.5;
ctx.fillText(text, x, y);
// from now on we'll draw behind current content
ctx.globalCompositeOperation = 'destination-over';
var shadow_pos = 0;
anim();
// in the anim, we just draw the shadow at a different offset every frame
function anim() {
if(shadow_pos++ > 65) return;
ctx.drawImage(shadow, shadow_pos, shadow_pos);
requestAnimationFrame(anim);
}
// returns a canvas where only the shadow of the text provided is drawn
function generateTextShadow(original_ctx, text, x, y, color, blur, offsetX, offsetY) {
var canvas = original_ctx.canvas.cloneNode();
var ctx = canvas.getContext('2d');
ctx.font = original_ctx.font;
var targetPosition = ctx.measureText(text).width + 2;
// default shadow settings
ctx.shadowColor = color || 'black';
ctx.shadowBlur = blur || 0;
ctx.shadowOffsetX = targetPosition + x +(offsetX ||0);
ctx.shadowOffsetY = (offsetY || 0);
ctx.fillText(text, -targetPosition, y);
return canvas;
}
<canvas id="canvas"></canvas>

DrawImage() doesn't draw on canvas

I am trying to make a screen following the player so that the player is in the middle of the screen. I have already made it in another game, but here it doesn't work. Here is my code :
var c = document.getElementById("main");
var ctx = c.getContext("2d");
var screen = document.getElementById("screen").getContext("2d");
var WhatUSeeWidth = document.getElementById("screen").width;
var WhatUSeeHeight = document.getElementById("screen").height;
ctx.beginPath();
for (i = 0; i < 100; i ++) {
if (i % 2) {
ctx.fillStyle = "red";
}
else {
ctx.fillStyle = "blue";
}
ctx.fillRect(0, i * 100, 500, 100);
}
var player = {
x : 700,
y : 800
}
setInterval(tick, 100);
function tick() {
screen.beginPath();
screen.drawImage(c, player.x - WhatUSeeWidth / 2, player.y - WhatUSeeHeight / 2, WhatUSeeWidth, WhatUSeeHeight, 0, 0, WhatUSeeWidth, WhatUSeeHeight);
}
canvas {
border: 2px solid black;
}
<canvas id="main" width="500" height="500"h></canvas>
<canvas id="screen" width="500" height="500"></canvas>
I want to draw The Blue and red canvas in The "screen" canvas Using drawImage
Ok , from your comment I understood what you are looking for. But the problem is that you probably start by an example without having understood. I try to give you my interpretation of what you do , but you should look for a good guide that starts with the basics and deepen animations (for example this: http://www.html5canvastutorials.com/).
HTML
<canvas id="canvasLayer" width="500" height="500"></canvas>
Javascript
var canvas = document.getElementById("canvasLayer");
var context = canvas.getContext("2d");
var WhatUSeeWidth = document.getElementById("canvasLayer").width;
var WhatUSeeHeight = document.getElementById("canvasLayer").height;
var player = {
x : 0,
y : 0
}
function drawBackground() {
for (i = 0; i < 100; i ++) {
if (i % 2) {
context.fillStyle = "red";
}
else {
context.fillStyle = "blue";
}
context.fillRect(0, i * 100, 500, 100);
}
}
function playerMove() {
context.beginPath();
var radius = 5;
context.arc(player.x, player.y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#003300';
context.stroke();
}
setInterval(tick, 100);
function tick() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
player.x++;
player.y++;
playerMove();
}
This is the JSFiddle.
EDIT WITH THE CORRECT ANSWER
The error is in the position of the object "player". It is located outside of the canvas, width:500 height:500 and the "player" is in position x:700 y:800.
Changing the position of the player your copy will appear.
var player = {
x : 50,
y : 50
}
Here the jsfiddle example.

Javascript confetti blast effect

I was able to find this code to create a javascript confetti blast.
However, I need three main colours for the confetti, and for the confetti, to be squares. Any help would be much appreciated.
Below is the code
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
W = window.innerWidth,
H = window.innerHeight,
circles = [];
canvas.width = W;
canvas.height = H;
//Random Circles creator
function create() {
//Place the circles at the center
this.x = W/2;
this.y = H/2;
//Random radius between 2 and 6
this.radius = 2 + Math.random()*3;
//Random velocities
this.vx = -5 + Math.random()*10;
this.vy = -5 + Math.random()*10;
//Random colors
this.r = Math.round(Math.random())*255;
this.g = Math.round(Math.random())*255;
this.b = Math.round(Math.random())*255;
}
for (var i = 0; i < 500; i++) {
circles.push(new create());
}
function draw() {
//Fill canvas with black color
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(0,0,0,0.15)";
ctx.fillRect(0, 0, W, H);
//Fill the canvas with circles
for(var j = 0; j < circles.length; j++){
var c = circles[j];
//Create the circles
ctx.beginPath();
ctx.arc(c.x, c.y, c.radius, 0, Math.PI*2, true);
ctx.fillStyle = "rgba("+c.r+", "+c.g+", "+c.b+", 1)";
ctx.fill();
c.x += c.vx;
c.y += c.vy;
c.radius -= .02;
if(c.radius > 3)
circles[j] = new create();
}
}
function animate() {
requestAnimFrame(animate);
draw();
}
animate();
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
body{
padding: 0; margin: 0;
min-height: 400px; height: 100%;
width: 100%;
overflow: hidden;
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="explosion.js"></script>
</body>
</html>
I wrote up an alternative solution. I noticed your current solutions had some runtime error, also a lot of unnecessary code (IMO - might be cleaner or easier to read?) and painted the whole rectangle canvas, you could apply this as a background colour via CSS, or leave as transparent as you probably want the confetti to show over something?
https://codepen.io/BenMoses/pen/MWyEePJ
ctx.globalCompositeOperation = "source-over"; //not needed as is default.
// shim layer with setTimeout fallback ? This is globally support so probably unnecessary?
//this.radius = 2 + Math.random()*3; //this is only for circles so can be removed
// all circle references should be updated to rect or square or confetti and confetto (a single confetti :o )
Pass in the index and use modulus operator to determine what color to set. Basic idea:
function create(ind) {
/* other code */
if(ind%3===0) { /* set color one */ }
else if (ind%2===0) { /* set color two */ }
else { /* set color three */ }
}
for (var i = 0; i < 500; i++) {
circles.push(new create(i));
}
Hopefully you figure out you need to change the this.r, this.g, and this.b values to match the color you need.
There are just a couple of places to modify (commented below).
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
padding: 0; margin: 0;
min-height: 400px; height: 100%;
width: 100%;
overflow: hidden;
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script>
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
W = window.innerWidth,
H = window.innerHeight,
circles = [];
canvas.width = W;
canvas.height = H;
//Random Circles creator
function create() {
//Place the circles at the center
this.x = W/2;
this.y = H/2;
//Random radius between 2 and 6
this.radius = 2 + Math.random()*3;
//Random velocities
this.vx = -5 + Math.random()*10;
this.vy = -5 + Math.random()*10;
}
for (var i = 0; i < 500; i++) {
circles.push(new create());
}
function draw() {
//Fill canvas with black color
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(0,0,0,0.15)";
ctx.fillRect(0, 0, W, H);
var myColors = ["e8e8e8", "a98547", "ccac7b"];
var which = 0;
//Fill the canvas with circles
for(var j = 0; j < circles.length; j++){
var c = circles[j];
//Create the circles
ctx.beginPath();
//ctx.arc(c.x, c.y, c.radius, 0, Math.PI*2, true);
ctx.fillRect(c.x , c.y, 20, 20); //change to box
//ctx.fillStyle = "rgba("+c.r+", "+c.g+", "+c.b+", 1)";
ctx.fillStyle = "#" + myColors[which].toString();
ctx.fill();
c.x += c.vx;
c.y += c.vy;
c.radius -= .02;
if(c.radius > 3)
circles[j] = new create();
if(which < myColors.length - 1) {
which++;
}
else {
which = 0;
}
}
}
function animate() {
requestAnimFrame(animate);
draw();
}
animate();
</script>
</body>
</html>
Here is the final code, thank you Stephen Brickner for all the help. I've learned a hell of alot
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
W = window.innerWidth,
H = window.innerHeight,
circles = [];
canvas.width = W;
canvas.height = H;
//Random Circles creator
function create() {
//Place the circles at the center
this.x = W/2;
this.y = H/2;
//Random radius between 2 and 6
this.radius = 2 + Math.random()*3;
//Random velocities
this.vx = -10 + Math.random()*30;
this.vy = -10 + Math.random()*30;
}
for (var i = 0; i < 100; i++) {
circles.push(new create());
}
function draw() {
//Fill canvas with black color
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(175,38,28,255)";
ctx.fillRect(0, 0, W, H);
var myColors = ["e8e8e8", "a98547", "ccac7b"];
var which = 0;
//Fill the canvas with circles
for(var j = 0; j < circles.length; j++){
var c = circles[j];
//Create the circles
ctx.beginPath();
//ctx.arc(c.x, c.y, c.radius, 0, Math.PI*2, true);
ctx.fillRect(c.x , c.y, 8, 8); //change to box
//ctx.fillStyle = "rgba("+c.r+", "+c.g+", "+c.b+", 1)";
ctx.fillStyle = "#" + myColors[which].toString();
ctx.fill();
c.x += c.vx;
c.y += c.vy;
c.radius -= .02;
if(c.radius > 3)
circles[j] = new create();
if(which < myColors.length - 1) {
which++;
}
else {
which = 0;
}
}
}
function animate() {
requestAnimFrame(animate);
draw();
}
animate();

Agario in JavaScript - Player not Moving

I am having problem with my code,
// JavaScript Document
var canvas = document.getElementById("PlayingArea");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var foodArray = [];
var size = 10;
var food;
var player1 = {x:150, y:150};
//create Player1
ctx.beginPath();
ctx.arc(150, 150, size, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
function update() {
"use strict";
//BG Refresh
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.strokeRect(0,0,canvasWidth,canvasHeight);
document.addEventListener("keydown", Player1Control);
function Player1Control(){
if(event.keyCode === 38) {
player1.y--;
}
if(event.keyCode === 40) {
player1.y++;
}
if(event.keyCode === 39) {
player1.x++;
}
if(event.keyCode === 37) {
player1.x--;
}
}
if (player1.x >= canvasWidth) {
player1.x = canvasWidth;
} else if (player1.x <= 5) {
player1.x = 5;
}
if (player1.y > canvasHeight) {
player1.y = canvasHeight;
} else if (player1.y <= 5) {
player1.y = 5;
}
//Player Show
ctx.beginPath();
ctx.arc(player1.x, player1.y, size, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
//Food Show
for(var i=foodArray.length; i>0; i--){
ctx.beginPath();
ctx.arc({x:foodArray[i].x},{y:foodArray[i].y} , size, 0, Math.PI * 2);
ctx.fill();
}
setTimeout(update, 10);
}
function foodGen(){
"use strict";
food = {x:Math.round(Math.random()*(canvasWidth)),
y:Math.round(Math.random()*(canvasHeight))};
ctx.beginPath();
ctx.arc(food.x, food.y, 5, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
foodArray.push({x:1,y:1});
setTimeout(foodGen, 1000);
}
update();
foodGen(0,750);
The player is not show in my code and I do not know why my player isn't Moving.
I am pretty new at JavaScript and HTML/CSS. This is my first time Stack overflow so I am sorry for any derps.
-lt1489
edit: My player now appears on the screen, can't be moved.
Link: https://jsfiddle.net/5os0qrhp/2/
The original question was answered with the following comment:
Since you don't change fillStyle between clearing the canvas and drawing the player, you are drawing the player white. Since it is white on white, you cannot see the player.
Regarding the second issue, move document.addEventListener and Player1Control to outside update. Additionally, Player1Control needs event as an argument, resulting in:
document.addEventListener("keydown", Player1Control);
function Player1Control(event) { ... }
function update() { ... }
A few syntax changes fixes the code. See jsfiddle to see those changes outlined.

Categories

Resources