javascript - multiple moving walls - javascript

I am making a game like flappy bird , the only difference is that the bird moves by using the mouse pointer location any where on the canvas. So for the obstacle i made walls but the walls are appearing in a bunch. I am not able to make walls that appear on regular interval in the canvas .
Required image :-
i am getting this :-
var context;
var screenWidth;
var screenHeight;
var ball;
var wall = [];
var gameStatus;
var mouseX;
var mouseY;
var running = false;
var raf;
gameIntialize();
gameDraw();
function Ball() {
this.radius = 16;
this.x = 25;
this.y = screenHeight / 2;
this.ballDraw = function() {
context.beginPath();
context.arc(this.x, this.y, 16, 0, 2 * Math.PI);
context.fillStyle = 'green';
context.fill();
}
};
function Wall() {
this.thickness = 10;
this.wallPositionY = screenHeight;
this.wallPositionX = screenWidth;
this.spacing = 0;
if (this.wallPositionY > 400 && this.wallPositionY <= 500) {
this.spacing = Math.floor(Math.random() * (100 - 50) + 50);
} else if (this.wallPositionY > 500) {
this.spacing = Math.floor(Math.random() * (200 - 100) + 100);
} else {
this.spacing = 45;
}
this.heightFromTheTop = Math.floor(Math.random() * (this.wallPositionY / 6 - 3 / 4 * this.wallPositionY) + this.wallPositionY);
this.heightFromTheBottom = this.wallPositionY - (this.heightFromTheTop + this.spacing);
this.speed = 6;
this.draw = function() {
context.fillStyle = 'yellow';
context.fillRect(this.wallPositionX, 0, this.thickness, this.heightFromTheTop);
context.fillRect(this.wallPositionX, this.wallPositionY - this.heightFromTheBottom, this.thickness, this.heightFromTheBottom);
}
this.update = function() {
this.wallPositionX = this.wallPositionX - this.speed;
}
this.offscreen = function() {
if (this.wallPositionX < -this.thickness) {
return true;
} else {
return false;
}
}
this.newWall = function() {
if (this.wallPositionX < screenWidth / 2) {
return true;
} else {
return false;
}
}
};
function gameIntialize() {
var canvass = document.getElementById('canvas');
context = canvas.getContext('2d');
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
canvas.width = screenWidth;
canvas.height = screenHeight;
ball = new Ball();
wall.push(new Wall());
// window.addEventListener('resize', resizeScreen, false);
canvas.addEventListener('mousemove', function(e) {
if (!running) {
ball.x = e.clientX;
ball.y = e.clientY;
}
});
}
function gameDraw() {
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, screenWidth, screenHeight);
ball.ballDraw();
for (var i = wall.length - 1; i >= 0; i--) {
wall[i].draw();
wall[i].update();
if (wall[i].offscreen()) {
wall.splice(i, 1);
}
var test_interval = setInterval(function() {
wall.push(new Wall());
}, 5000);
}
raf = window.requestAnimationFrame(gameDraw);
}
body {
margin: 0px
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>game-run</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="game.js"></script>
</html>
What is wrong with this code? I appreciate any help!

Your setInterval creation code is sitting inside your game loop.
That means you're creating a new 5 second interval for EVERY FRAME!
Take it out of there and things should be fine.
Modified snippet:
var context;
var screenWidth;
var screenHeight;
var ball;
var wall = [];
var gameStatus;
var mouseX;
var mouseY;
var running = false;
var raf;
gameIntialize();
gameDraw();
function Ball() {
this.radius = 16;
this.x = 25;
this.y = screenHeight / 2;
this.ballDraw = function() {
context.beginPath();
context.arc(this.x, this.y, 16, 0, 2 * Math.PI);
context.fillStyle = 'green';
context.fill();
}
};
function Wall() {
this.thickness = 10;
this.wallPositionY = screenHeight;
this.wallPositionX = screenWidth;
this.spacing = 0;
if (this.wallPositionY > 400 && this.wallPositionY <= 500) {
this.spacing = Math.floor(Math.random() * (100 - 50) + 50);
} else if (this.wallPositionY > 500) {
this.spacing = Math.floor(Math.random() * (200 - 100) + 100);
} else {
this.spacing = 45;
}
this.heightFromTheTop = Math.floor(Math.random() * (this.wallPositionY / 6 - 3 / 4 * this.wallPositionY) + this.wallPositionY);
this.heightFromTheBottom = this.wallPositionY - (this.heightFromTheTop + this.spacing);
this.speed = 6;
this.draw = function() {
context.fillStyle = 'yellow';
context.fillRect(this.wallPositionX, 0, this.thickness, this.heightFromTheTop);
context.fillRect(this.wallPositionX, this.wallPositionY - this.heightFromTheBottom, this.thickness, this.heightFromTheBottom);
}
this.update = function() {
this.wallPositionX = this.wallPositionX - this.speed;
}
this.offscreen = function() {
if (this.wallPositionX < -this.thickness) {
return true;
} else {
return false;
}
}
this.newWall = function() {
if (this.wallPositionX < screenWidth / 2) {
return true;
} else {
return false;
}
}
};
function gameIntialize() {
var canvass = document.getElementById('canvas');
context = canvas.getContext('2d');
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
canvas.width = screenWidth;
canvas.height = screenHeight;
ball = new Ball();
wall.push(new Wall());
// window.addEventListener('resize', resizeScreen, false);
canvas.addEventListener('mousemove', function(e) {
if (!running) {
ball.x = e.clientX;
ball.y = e.clientY;
}
});
}
function gameDraw() {
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, screenWidth, screenHeight);
ball.ballDraw();
for (var i = wall.length - 1; i >= 0; i--) {
wall[i].draw();
wall[i].update();
if (wall[i].offscreen()) {
wall.splice(i, 1);
}
}
raf = window.requestAnimationFrame(gameDraw);
}
var test_interval = setInterval(function() {
wall.push(new Wall());
}, 1500);
body {
margin: 0px
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>game-run</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="game.js"></script>
</html>

Related

How to make bullet launcher point in mouse position? Canvas JavaScript

When the mouse moves it doesn't point in the mouseX or mouseY direction.
The current method points and rotates at the top right point slightly offset on the canvas.
All the other SO questions didn't work for this specific game.
I would prefer the most straightforward answer and an explanation of how it works.
I need a vanilla javascript answer.
/**
* #type { HTMLCanvasElement }
*/
var scene = document.getElementById("scene");
var ctx = scene.getContext("2d");
var mouseX = 0;
var mouseY = 0;
var prevSceneTranslateXL = 0;
var prevSceneTranslateYL = 0;
var prevSceneTranslateXR = 0;
var prevSceneTranslateYR = 0;
var sceneTranslateX = 0;
var sceneTranslateY = 0;
var friction = 4 / 5;
var keysDown = [];
scene.width = window.innerWidth;
scene.height = window.innerHeight;
var bg = new Image();
bg.src = "./assets/groundBgAlt.png";
class Player {
constructor(x, y, radius, color, borderColor) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.borderColor = borderColor;
this.velX = 0;
this.velY = 0;
this.speed = 15;
this.angle = 0;
}
}
class Enemy {
constructor(radius, color, borderColor) {
this.x = Math.random() * scene.width + 25;
this.y = Math.random() * scene.height + 25;
this.radius = radius;
this.color = color;
this.borderColor = borderColor;
this.velX = 0;
this.velY = 0;
this.speed = 15;
this.angle = 0;
}
}
var player1 = new Player(1000, 1000, 25, "#0080ff", "#606060");
var enemies = [];
// for (i = 0; i < 20; i++) {
// enemies.push(new Enemy(50, 50, "#ff0000", "#bb0000"));
// }
function drawPlayer(player) {
ctx.strokeStyle = "#606060";
ctx.lineWidth = 2;
ctx.fillStyle = "#cccccc";
ctx.save();
ctx.beginPath();
ctx.translate(player.x, player.y);
ctx.rotate(player1.angle);
ctx.roundRect(-10, -45, 20, 25, 2);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.strokeStyle = player.borderColor;
ctx.lineWidth = 2;
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.arc(player.x, player.y, player.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
function drawEnemies(enemy) {
ctx.strokeStyle = enemy.borderColor;
ctx.lineWidth = 3;
ctx.fillStyle = enemy.color;
ctx.beginPath();
ctx.rect(enemy.x, enemy.y, enemy.width, enemy.height);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
var gradientBG = ctx.createRadialGradient(1000, 1000, 1000, 1000, 1000, 100);
gradientBG.addColorStop(0.0, "#ffffff");
gradientBG.addColorStop(1.0, "#eeeeee");
function main() {
ctx.clearRect(-250, -250, 2500, 2500);
ctx.fillStyle = gradientBG;
ctx.fillRect(0, 0, 2000, 2000);
if (player1.x < 0) {
sceneTranslateX = prevSceneTranslateXL;
player1.x = 0;
player1.velX = 0;
}
if (player1.x > 2000) {
sceneTranslateX = prevSceneTranslateXR;
player1.x = 2000;
player1.velX = 0;
}
if (player1.y < 0) {
sceneTranslateY = prevSceneTranslateYL;
player1.y = 0;
player1.velY = 0;
}
if (player1.y > 2000) {
sceneTranslateY = prevSceneTranslateYR;
player1.y = 2000;
player1.velY = 0;
}
if (keysDown["w"] || keysDown["ArrowUp"]) {
if (player1.velY > player1.speed * -1) {
player1.velY--;
}
}
if (keysDown["a"] || keysDown["ArrowLeft"]) {
if (player1.velX > player1.speed * -1) {
player1.velX--;
}
}
if (keysDown["s"] || keysDown["ArrowDown"]) {
if (player1.velY < player1.speed) {
player1.velY++;
}
}
if (keysDown["d"] || keysDown["ArrowRight"]) {
if (player1.velX < player1.speed) {
player1.velX++;
}
}
player1.velX *= friction;
player1.velY *= friction;
player1.x += player1.velX;
player1.y += player1.velY;
sceneTranslateX *= friction;
sceneTranslateY *= friction;
sceneTranslateX += -player1.velX;
sceneTranslateY += -player1.velY;
prevSceneTranslateXL = sceneTranslateX - 1;
prevSceneTranslateYL = sceneTranslateY - 1;
prevSceneTranslateXR = sceneTranslateX + 1;
prevSceneTranslateYR = sceneTranslateY + 1;
ctx.translate(sceneTranslateX / 5, sceneTranslateY / 5);
drawPlayer(player1);
// for (i = 0; i < enemies.length; i++) {
// drawEnemies(enemies[i]);
// }
requestAnimationFrame(main);
}
ctx.translate((scene.width / 2) - player1.x, (scene.height / 2) - player1.y);
main();
document.addEventListener("keydown", (e) => {
keysDown[e.key] = true;
});
document.addEventListener("keyup", (e) => {
keysDown[e.key] = false;
});
document.addEventListener("mousemove", (e) => {
var angle = Math.atan2(e.pageY - player1.y, e.pageX - player1.x);
player1.angle = angle;
});
* {
font-family: roboto, Arial, Helvetica, sans-serif, system-ui, system 'Courier New', Courier, monospace;
padding: 0px 0px;
margin: 0px 0px;
box-sizing: border-box;
}
body {
background: radial-gradient(circle, #bbbbbb 10%, #cccccc);
overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/styles.css">
<script src="scripts/index.js" defer></script>
<title>Document</title>
</head>
<body>
<canvas id="scene" width="1024" height="576"></canvas>
</body>
</html>
The way the game is made makes it really hard to rotate objects.

Why is my image width and height equal to 0? [duplicate]

This question already has an answer here:
CanvasContext2D drawImage() issue [onload and CORS]
(1 answer)
Closed 4 years ago.
I am trying to make a infinite scrolling game in javascript.
The following code works as expected (it doesn't work here because the images cannot be uploaded):
class Vec {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
class Rect {
constructor(src) {
this.pos = new Vec;
this.vel = new Vec;
this.image = new Image();
this.image.src = src;
}
get left() {
return this.pos.x;
}
get right() {
return this.pos.x + this.image.width;
}
get top() {
return this.pos.y;
}
get bottom() {
return this.pos.y + this.image.height;
}
}
class Player extends Rect {
constructor() {
super("images/frog-still.png");
this.pos.x = 100;
this.pos.y = HEIGHT - GROUND_Y - this.image.height;
}
}
class Enemy extends Rect {
constructor() {
super("images/spike.png");
this.image.width = this.image.width / 4;
this.image.height = this.image.height / 4;
this.pos.x = WIDTH;
this.pos.y = HEIGHT - GROUND_Y - this.image.height;
}
}
// setup
const ctx = document.getElementById("canvas").getContext("2d");
let isOver = false;
const WIDTH = 600;
const HEIGHT = 400;
const GROUND_Y = 50;
const player = new Player;
let enemies = [];
const MAX_ENEMY = 3;
let isJumping = false;
const JUMP_STRENGTH = -450;
const GRAVITY = 25;
document.addEventListener("keydown", (e) => {
if (e.keyCode === 38 && isJumping === false) {
isJumping = true;
player.vel.y = JUMP_STRENGTH;
}
}, false);
let lastUpdate = 0;
let random = Math.floor((Math.random() * 2501) + 1000);
function update(dt, now) {
// update player
player.vel.y += GRAVITY;
player.pos.y += player.vel.y * dt;
if (player.bottom >= HEIGHT - GROUND_Y) {
isJumping = false;
player.pos.y = HEIGHT - GROUND_Y - player.image.height;
player.vel.y = 0;
}
// create enemy
if (now - lastUpdate > random) {
lastUpdate = now;
random = Math.floor((Math.random() * 2501) + 1000);
enemies.push(new Enemy);
}
for (let i = 0; i < enemies.length; i++) {
// update enemy
enemies[i].vel.x = -300 - (now / 500);
enemies[i].pos.x += enemies[i].vel.x * dt;
if (player.right > enemies[i].left && player.left < enemies[i].right && player.bottom > enemies[i].top)
isOver = true;
if (enemies[i].right < 0)
enemies.splice(i, 1);
}
}
function draw() {
// draw background
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// draw ground
ctx.fillStyle = "#0f0";
ctx.fillRect(0, HEIGHT - GROUND_Y, WIDTH, GROUND_Y);
// draw player
ctx.drawImage(player.image, player.pos.x, player.pos.y, player.image.width, player.image.height);
// draw enemy
ctx.fillStyle = "#f00";
for (let i = 0; i < enemies.length; i++) {
ctx.drawImage(enemies[i].image, enemies[i].pos.x, enemies[i].pos.y, enemies[i].image.width, enemies[i].image.height);
}
}
// game loop
const TIMESTEP = 1 / 60;
let accumulator = 0;
let lastRender = 0;
function loop(timestamp) {
accumulator += (timestamp - lastRender) / 1000;
lastRender = timestamp;
while (accumulator >= TIMESTEP) {
update(TIMESTEP, timestamp);
accumulator -= TIMESTEP;
}
draw();
if (!isOver)
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
<!DOCTYPE html>
<html>
<head>
<title>Jump_Over_It</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script src="js/main.js"></script>
</body>
</html>
However, when add
this.image.width = this.image.width / 2;
this.image.height = this.image.height / 2;
to the Player class (like I did with the Enemy class), the player disappears. If I do console.log(player.image), it says that the image width and the image height is equal to 0. Why is this happening?
How can I fix this problem?
I don't know why, but while the image is not rendered the width and height are 0. So, I created the method beforeRender() that is implemented by Player and Enemy. This method is invoked before the ctx.drawImage and update the graphics settings.
I know it is not the answer you are looking for, but it is my best.
class Vec {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
class Rect {
constructor(src) {
this.pos = new Vec;
this.vel = new Vec;
this.image = new Image;
this.image.src = src;
this.rendered = false;
}
get left() {
return this.pos.x;
}
get right() {
return this.pos.x + this.image.width;
}
get top() {
return this.pos.y;
}
get bottom() {
return this.pos.y + this.image.height;
}
get render() {
if (!this.rendered) {
if (this.beforeRender()) {
this.rendered = true;
}
}
return this.image;
}
beforeRender() {}
}
class Player extends Rect {
constructor() {
super("https://cdn4.iconfinder.com/data/icons/spring-flat-colorful/2048/5683_-_Frog-256.png");
this.pos.x = 100;
this.pos.y = HEIGHT - GROUND_Y - this.image.height;
}
beforeRender() {
if (this.image.width && this.image.height) {
this.image.width /= 2;
this.image.height /= 2;
return true;
}
return false;
}
}
class Enemy extends Rect {
constructor() {
super("https://vignette.wikia.nocookie.net/scribblenauts/images/8/8d/Steel_Spike.png/revision/latest?cb=20130105173440");
this.image.width /= 4;
this.image.height /= 4;
this.pos.x = WIDTH;
this.pos.y = HEIGHT - GROUND_Y - this.image.height;
}
beforeRender() {
if (this.image.width && this.image.height) {
this.image.width /= 4;
this.image.height /= 4;
return true;
}
return false;
}
}
// setup
const ctx = document.getElementById("canvas").getContext("2d");
let isOver = false;
const WIDTH = 600;
const HEIGHT = 400;
const GROUND_Y = 50;
const player = new Player;
let enemies = [];
const MAX_ENEMY = 3;
let isJumping = false;
const JUMP_STRENGTH = -450;
const GRAVITY = 25;
document.addEventListener("keydown", (e) => {
if (e.keyCode === 38 && isJumping === false) {
isJumping = true;
player.vel.y = JUMP_STRENGTH;
}
}, false);
let lastUpdate = 0;
let random = Math.floor((Math.random() * 2501) + 1000);
function update(dt, now) {
// update player
player.vel.y += GRAVITY;
player.pos.y += player.vel.y * dt;
if (player.bottom >= HEIGHT - GROUND_Y) {
isJumping = false;
player.pos.y = HEIGHT - GROUND_Y - player.image.height;
player.vel.y = 0;
}
// create enemy
if (now - lastUpdate > random) {
lastUpdate = now;
random = Math.floor((Math.random() * 2501) + 1000);
enemies.push(new Enemy);
}
for (let i = 0; i < enemies.length; i++) {
// update enemy
enemies[i].vel.x = -300 - (now / 500);
enemies[i].pos.x += enemies[i].vel.x * dt;
if (player.right > enemies[i].left && player.left < enemies[i].right && player.bottom > enemies[i].top)
isOver = true;
if (enemies[i].right < 0)
enemies.splice(i, 1);
}
}
function draw() {
// draw background
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// draw ground
ctx.fillStyle = "#0f0";
ctx.fillRect(0, HEIGHT - GROUND_Y, WIDTH, GROUND_Y);
// draw player
ctx.drawImage(player.render, player.pos.x, player.pos.y, player.image.width, player.image.height);
// draw enemy
ctx.fillStyle = "#f00";
for (let i = 0; i < enemies.length; i++) {
ctx.drawImage(enemies[i].image, enemies[i].pos.x, enemies[i].pos.y, enemies[i].image.width, enemies[i].image.height);
}
}
// game loop
const TIMESTEP = 1 / 60;
let accumulator = 0;
let lastRender = 0;
requestAnimationFrame(loop);
function loop(timestamp) {
accumulator += (timestamp - lastRender) / 1000;
lastRender = timestamp;
while (accumulator >= TIMESTEP) {
update(TIMESTEP, timestamp);
accumulator -= TIMESTEP;
}
draw();
if (!isOver)
requestAnimationFrame(loop);
}
<!DOCTYPE html>
<html>
<head>
<title>Jump_Over_It</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script src="js/main.js"></script>
</body>
</html>

Moving an Object according to mouse coordinates

How do I get the following script to work? I wanted to be able to move the ship to the mouse coordinates. The space itself should move and the ship should stay in the centerview.
Would be great if you can modify the script as everybody writes his functions different.
Finally if the button is clicked I want the ship to move to that destination
I tried it when it worked and the ship never moved and I don't know if it has to do with the prototype.update function or not.
Is prototype.update or .render the same as if I would write this.update or this.render?
<script>
function domanDown(evt)
{
switch (evt)
{
case 38: /* Up arrow was pressed or button pressed*/
offsetY+=100 ;
break;
case 40: /* Down arrow was pressed or button pressed*/
offsetY-=100;
break;
case 37: /* Left arrow was pressedor button pressed*/
offsetX+=100;
break;
case 39: /* Right arrow was pressed or button pressed*/
offsetX-=100;
break;
}
}
window.requestAnimationFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
var Obj = function (x,y,sp,size){
this.size = size;
this.x = x;
this.y = y;
this.color = sp;
this.selected = 0;
}
var Planet_Class = function (x,y,sp){
this.type = 'Planet_Class';
this.depot = 11;
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Planet_Class.prototype.update =function () {
}
Planet_Class.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var Usership = function(x,y,sp){
this.depot = 10;
this.type = 'Usership';
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Usership.prototype.update =function (x,y) {
this.xtype.x = x || 20;
this.xtype.y = y || 20;
}
Usership.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var World = function(){
this.objects = new Array();
this.count = function(type,sp){
var cnt = 0;
for(var k = 0;k<this.objects.length;k++)
cnt++;
return cnt;
}
}
renderWorld = function(){
requestAnimationFrame(renderWorld);
var spliceArray = Array();
ctx.beginPath();
objcnt = w.objects.length;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.fill();
i = 0;
while(i < objcnt){
w.objects[i].update();
w.objects[i].render();
if(w.objects[i].depot < 1)
spliceArray.push(i);
i++;
}
for(var k = 0;k<spliceArray.length;k++)
{
w.objects.splice(spliceArray[k],1); }
}
function r1(max,min){
return (Math.floor(Math.random() * (max - min)) + 1);
}
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d"),
width = 1024,
height = 768;
offsetX = (canvas.width/2)-300; /Startpoint x for the Ship
offsetY = (canvas.height/2)-300; /Startpoint y for the Ship
generateshipx = -offsetX + (canvas.width/2);
generateshipy = -offsetY + (canvas.height/2);
mX = generateshipx;
mY = generateshipy;
w = new World();
new Usership(generateshipx,generateshipy,'green');
for(i=1;i<4;i++){
new Planet_Class(r1(600,2),r1(600,2),'red');
}
canvas.addEventListener("click", function (e) {
mX = e.pageX- canvas.offsetLeft -offsetX) ;
mY = e.pageY - canvas.offsetTop -offsetY) ;
});
renderWorld();
</script>
<html>
<head>
</head>
<body style="background-color:black;">
<canvas style="z-index:1" width="1024" height="768" id="canvas"></canvas>
<input type="button" style="z-index:2; position:absolute; top:300; left:10" value="uo" onCLick="domanDown(38)()">
<input type="button" style="z-index:2; position:absolute; top:340; left:10" value="down" onCLick="domanDown(40)">
<input type="button" style="z-index:2; position:absolute; top:380; left:10" value="left" onCLick="domanDown(37)">
<input type="button" style="z-index:2; position:absolute; top:420; left:10" value="right" onCLick="domanDown(39)">
<input type="button" style="z-index:2; position:absolute; top:460; left:10" value="move" onCLick="moveObj()">
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
cursor: crosshair;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var bounds = null;
var isRotating = false;
var isMoving = false;
var pan = {
x: 0.0,
y: 0.0
};
var target = {
x: 0.0,
y: 0.0,
dist: 0.0
};
var ship = {
x: (canvasWidth * 0.5)|0,
y: (canvasHeight * 0.5)|0,
width: 10.0,
height: 10.0,
rotation: 0.0,
deltaRotation: 0.0
};
var stars = [];
stars.length = 100;
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
bounds = canvas.getBoundingClientRect();
for (var i = 0; i < stars.length; ++i) {
stars[i] = {
x: (Math.random() * 4 * canvasWidth - 2 * canvasWidth)|0,
y: (Math.random() * 4 * canvasHeight - 2 * canvasHeight)|0
};
}
loop();
}
window.onmousedown = function(e) {
isRotating = true;
isMoving = false;
target.x = pan.x + e.clientX - bounds.left;
target.y = pan.y + e.clientY - bounds.top;
}
function loop() {
// Tick
// Rotate to face target
if (isRotating) {
// Vector creation
var tX = ship.x - target.x;
var tY = ship.y - target.y;
var tL = Math.sqrt(tX**2 + tY**2);
var fX = Math.sin(ship.rotation);
var fY = -Math.cos(ship.rotation);
var sX = Math.sin(ship.rotation + Math.PI * 0.5);
var sY = -Math.cos(ship.rotation + Math.PI * 0.5);
// Normalization
tX = tX / tL;
tY = tY / tL;
// Left or right?
var a = 1.0 - Math.abs(tX * fX + tY * fY);
ship.rotation += 0.075 * (sX * tX + sY * tY < 0.0 ? 1.0 : -1.0);
if (a < 0.01) {
target.dist = tL;
isRotating = false;
isMoving = true;
}
}
// Accelerate to target
if (isMoving) {
ship.x += Math.sin(ship.rotation) * 1.0;
ship.y -= Math.cos(ship.rotation) * 1.0;
if (--target.dist < 0.0) {
isMoving = false;
}
}
// Render
// Update pan coordinates
pan.x = ship.x - canvasWidth * 0.5;
pan.y = ship.y - canvasHeight * 0.5;
// Draw background
ctx.fillStyle = "#222222";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.fillStyle = "white";
for (var i = 0; i < stars.length; ++i) {
ctx.fillRect(
stars[i].x - pan.x,
stars[i].y - pan.y,
2,
2
);
}
// Draw ship
ctx.strokeStyle = "white";
ctx.fillStyle = "darkred";
ctx.translate(canvasWidth * 0.5,canvasHeight * 0.5);
ctx.rotate(ship.rotation);
ctx.beginPath();
ctx.moveTo(-ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(0.0,-ship.height * 0.5);
ctx.lineTo(-ship.width * 0.5,ship.height * 0.5);
ctx.fill();
ctx.stroke();
ctx.rotate(-ship.rotation);
ctx.translate(-canvasWidth * 0.5,-canvasHeight * 0.5);
requestAnimationFrame(loop);
}
</script>
</body>
</html>

Resizing a <canvas> Element

I have the following canvas. I'm trying to make it smaller using the width and height attributes, but it doesn't work. This is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="canvas" width="200" height="50"></canvas>
<script>
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
w = a.width = window.innerWidth,
h = a.height = window.innerHeight,
area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - .05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if(this.r <= .05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++) {
if(particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if(particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for(var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max)?max:1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
</script>
</body>
</html>
Pay more attention here:
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
w = a.width = window.innerWidth,
h = a.height = window.innerHeight,
area = w * h,
As you can see, w is the width of the window and h is the height of the window. Try to edit w and h variable with custom values and tell me if it worked ;)
EDIT:
Simply replace h and w with this in your script tag:
a.style.width = '500px'; //random value, insert custom here
a.style.height = '500px';

why doesn't this code animate anything?

I am trying to create a blackhole simulation, here is the code, now the problem is that my code doesn't display anything, I tried a code beautifier, but it did not work, so what is wrong with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script>
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector (0,0);
var forceDirection2 = Math.atan2(pos.y - 400, pos.x - 700);
var g = (pixel_G*pixel_M)/(distance*distance*1e3);
delta2.x += Math.cos(forceDirection2) * g;
delta2.y += Math.sin(forceDirection2) *g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 0.50;
if (pos.x = 700 && pos.y = 400){
somethingMoved = false;
}
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init() {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, {
x: 700,
y: 400
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c=parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick (){
canvas = document.getElementById ('space');
ctx = canvas.getContext ('2d')
canvas.addEventListener ("mousedown", init, false)
blackhole = new Ball (5, {
x: 700,
y: 400
}, 0);
blackhole.draw (ctx) ;
}
window.onload = onClick;
</script>
<style>
body {
background-color:#021c36 ;
margin: 0px;}
</style>
</head>
<body>
<canvas id = "space", width = "1400", height = "800">
</canvas>
</body>
</html>
now the problem as you can see, is that i can't make it display anything, so if someone can tell me why it'd be great
Ps: I think the problem comes from the update function but i am not sure
You had a ReferenceError: invalid assignment left-hand side on line 44:
Your code:
if (pos.x = 700 && pos.y = 400)
Just change this to:
if (pos.x == 700 && pos.y == 400){
That should work.

Categories

Resources