Canvas: X value changing in console but not in canvas - javascript

I am pulling coordinates from an API and setting them to a class of Rectangle. When looping through the data array, I am able to create each rectangle, but when it comes to moving them, that is where I am having trouble.
The x coordinates are changing in the console at the setInterval of move(), but the squares themselves are not moving across the screen.
When I have c.clearRect(0,0,innerWidth, innerHeight); in move(), all of the rectangles disappear. Without it, they do not move at all.
if(this % 6 === 0){
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
is referring to the data array and if the index is divisible by 6, make that square black. Although, in this context, it is not working.
Here is my code:
<script>
const canvas = document.getElementById("canvas");
const c = canvas.getContext('2d');
let xhReq = new XMLHttpRequest();
xhReq.open("GET", "(api here)", false);
xhReq.send(null);
const data = JSON.parse(xhReq.responseText);
class Rectangle {
constructor(x, y, w, h, vx, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = vx;
this.color = color;
}
draw() {
c.fillRect(this.x, this.y, this.w, this.h);
if(this % 6 === 0){
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
}
}
move(){
c.clearRect(0,0,innerWidth, innerHeight);
if (this.x > 800 || this.x < 0){
this.vx = -this.vx;
}
this.x+= this.vx;
c.beginPath();
console.log("here is the x value:" + this.x);
}
}
for(let i=0; i<data.length; i++){
let info = data[i]
let rec = new Rectangle(info.x, info.y, info.w, info.h, info.vx, info.color);
rec.draw();
setInterval(function() {
rec.move();
}, 50);
}
</script>

There are a lot of issues with your code.
You are only updating the position and not making the draw call again.
Move the rec.draw() call inside your setInterval. Remember, ordering is important. Ideally, you should update() first and draw() later.
setInterval(function() {
rec.move();
rec.draw();
}, 50);
Also, remove these lines from the move() function as you don't want to clear the canvas every time you update the variables. Clear the canvas in the beginning of the draw() function. Plus, since you're dealing with fillRect(), you dont need to include beginPath()
c.clearRect(0,0,innerWidth, innerHeight);
...
c.beginPath();
You first need to specify the fillStyle then proceed with drawing the rectangle using fillRect(), not the other way round. The draw() function should look like this:
draw() {
c.clearRect(0, 0, innerWidth, innerHeight);
if(this % 6 === 0){ // <-- Not really sure what is going on here
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
}
c.fillRect(this.x, this.y, this.w, this.h);
}
In the code block in point number #3 you are using the Modulus Operator % on the the instance of the class itself i.e. this and not a number. I'm assuming you want something like this.x in there.
Apart from the points above there are still a handful of issues with your code. But it's outside the context of this question.
Edited for a final solution below:
const canvas = document.getElementById("canvas");
const context = canvas.getContext('2d');
const xhr = new XMLHttpRequest();
// Usng var as we are making an async request and need to update this variable
var data = null;
// An empty array to store our rectangles
var collection = [];
// Using an asyn request as we don't necessarily need to wait for this step
xhr.open('GET', '<api>', true)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
data = JSON.parse(xhr.responseText);
dataLoaded();
} else {
// The request gave an error response
}
}
};
xhr.send();
function dataLoaded(){
for(let i = 0; i < data.length; i++){
let info = data[i];
collection.push(new Rectangle(info.x, info.y, info.w, info.h, info.vx, info.color));
}
setInterval(animate, 50);
}
function animate(){
context.clearRect(0, 0, canvas.width, canvas.height);
for(let i = 0; i < collection.length; i++){
let rect = collection[i];
rect.update();
rect.draw();
}
}
class Rectangle {
constructor(x, y, w, h, vx, color){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = vx;
this.color = color;
}
update(){
if (this.x > 800 || this.x < 0){
this.vx = -this.vx;
}
this.x += this.vx;
}
draw(){
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.w, this.h);
}
}

Related

"OOP" in canvas correct way

I'm trying to draw something on canvas with sugar code that we received not that long time ago. I'm using babel of course. I have two questions. First of all you can find my code below:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fillStyle = "#000";
ctx.fill();
ctx.closePath();
};
move() {
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.x--
this.draw();
}
if (event.keyCode === 39) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.x++
this.draw();
}
})
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
};
}
const rect = new Rectangle(130, 50);
const ball = new Ball(60, 40)
setInterval(() => {
rect.draw();
rect.move();
ball.draw();
}, 100);
I made two classes. One is rectangle, second ball. Rectangle is the one that can move with arrows. When i move, ball disapears for a brief second, then appears on the screen again. What am i doing wrong in this case? How game flow should look like properly?
Second question is: how can i make these two classes interract with each other? For example, i want that when rectangle will touch ball simple console.log will apear. Thanks
Most of the code is yours. Since I prefer using requestAnimationFrame I'm adding an identifier for the request: let requestId = null;.
The move() method of the rectangle deals only with the value of x, and takes the key as an attribute.
Also I've written the frame function that builds your animation frame by frame.
function frame() {
requestId = window.requestAnimationFrame(frame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect.move(key);
rect.draw();
ball.draw();
}
On keydown you change the value for the key variable, you cancel the current animation, and you call the frame function to start a new animation.
I've added as well a keyup event to stop the animation on key up.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let key;
let requestId = null;
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fillStyle = "#000";
ctx.fill();
//ctx.closePath();
}
move(key) {
if (key == 37) {
this.x--;
}
if (key == 39) {
this.x++;
}
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
//ctx.closePath();
}
}
const rect = new Rectangle(130, 50);
const ball = new Ball(60, 40);
rect.draw();
ball.draw();
function frame() {
requestId = window.requestAnimationFrame(frame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect.move(key);
rect.draw();
ball.draw();
}
document.addEventListener("keydown", event => {
if (requestId) {
window.cancelAnimationFrame(requestId);
}
key = event.keyCode;
frame();
});
document.addEventListener("keyup", event => {
if (requestId) {
window.cancelAnimationFrame(requestId);
}
});
canvas{border:1px solid;}
<canvas id="myCanvas"></canvas>
PS: Please read this article requestAnimationFrame for Smart Animating

Loop Background Image Animation in Canvas

I am new to Canvas and want to loop background Image in the below smoke effect. On searching, I have found an example that how we can loop background Image in canvas Link to looping animation so I tried integrating the looping code with the smoke effect but no success. Any help will be appreciated.
// Create an array to store our particles
var particles = [];
// The amount of particles to render
var particleCount = 60;
// The maximum velocity in each direction
var maxVelocity = 2;
// The target frames per second (how often do we want to update / redraw the scene)
var targetFPS = 33;
// Set the dimensions of the canvas as variables so they can be used.
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
// borders for particles on top and bottom
var borderTop = 0.01 * canvasHeight;
var borderBottom = 0.99 * canvasHeight;
// Create an image object (only need one instance)
var imageObj = new Image();
var looping = false;
var totalSeconds = 0;
// Once the image has been downloaded then set the image on all of the particles
imageObj.onload = function() {
particles.forEach(function(particle) {
particle.setImage(imageObj);
});
};
// Once the callback is arranged then set the source of the image
imageObj.src = "https://image.ibb.co/fdpeJF/Smoke.png";
// A function to create a particle object.
function Particle(context) {
// Set the initial x and y positions
this.x = 0;
this.y = 0;
// Set the initial velocity
this.xVelocity = 0;
this.yVelocity = 0;
// Set the radius
this.radius = 5;
// Store the context which will be used to draw the particle
this.context = context;
// The function to draw the particle on the canvas.
this.draw = function() {
// If an image is set draw it
if (this.image) {
this.context.drawImage(this.image, this.x - 128, this.y - 128);
// If the image is being rendered do not draw the circle so break out of the draw function
return;
}
// Draw the circle as before, with the addition of using the position and the radius from this object.
this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
this.context.fillStyle = "rgba(0, 255, 255, 1)";
this.context.fill();
this.context.closePath();
};
// Update the particle.
this.update = function() {
// Update the position of the particle with the addition of the velocity.
this.x += this.xVelocity;
this.y += this.yVelocity;
// Check if has crossed the right edge
if (this.x >= canvasWidth) {
this.xVelocity = -this.xVelocity;
this.x = canvasWidth;
}
// Check if has crossed the left edge
else if (this.x <= 0) {
this.xVelocity = -this.xVelocity;
this.x = 0;
}
// Check if has crossed the bottom edge
if (this.y >= borderBottom) {
this.yVelocity = -this.yVelocity;
this.y = borderBottom;
}
// Check if has crossed the top edge
else if (this.y <= borderTop) {
this.yVelocity = -this.yVelocity;
this.y = borderTop;
}
};
// A function to set the position of the particle.
this.setPosition = function(x, y) {
this.x = x;
this.y = y;
};
// Function to set the velocity.
this.setVelocity = function(x, y) {
this.xVelocity = x;
this.yVelocity = y;
};
this.setImage = function(image) {
this.image = image;
};
}
// A function to generate a random number between 2 values
function generateRandom(min, max) {
return Math.random() * (max - min) + min;
}
// The canvas context if it is defined.
var context;
// Initialise the scene and set the context if possible
function init() {
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (canvas.getContext) {
// Set the context variable so it can be re-used
context = canvas.getContext('2d');
// Create the particles and set their initial positions and velocities
for (var i = 0; i < particleCount; ++i) {
var particle = new Particle(context);
// Set the position to be inside the canvas bounds
particle.setPosition(generateRandom(0, canvasWidth), generateRandom(borderTop, borderBottom));
// Set the initial velocity to be either random and either negative or positive
particle.setVelocity(generateRandom(-maxVelocity, maxVelocity), generateRandom(-maxVelocity, maxVelocity));
particles.push(particle);
context.clearRect(0, 0, canvas.width, canvas.height);
}
} else {
alert("Please use a modern browser");
}
}
// The function to draw the scene
function draw() {
// background image
context.globalAlpha = 1;
context.globalCompositeOperation = 'source-over';
context.drawImage(backImg, 0, 0, canvasWidth, canvasHeight);
context.fillStyle = "rgba(255,255,255, .5)";
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.globalAlpha = 0.75;
context.globalCompositeOperation = 'soft-lights';
// Fog layer
// Go through all of the particles and draw them.
particles.forEach(function(particle) {
particle.draw();
});
}
// Update the scene
function update() {
particles.forEach(function(particle) {
particle.update();
});
}
// Initialize the scene
init();
backImg = new Image();
backImg.src = 'https://image.ibb.co/cTOOdF/e2VZQY.jpg';
// If the context is set then we can draw the scene (if not then the browser does not support canvas)
if (context) {
setInterval(function() {
// Update the scene befoe drawing
update();
// Draw the scene
draw();
}, 1000 / targetFPS);
}
<canvas id="myCanvas" ></canvas>
I just added a few lines. Hopefully you can spot them. I commented everything I added.
// Create an array to store our particles
var particles = [];
// The amount of particles to render
var particleCount = 60;
// The maximum velocity in each direction
var maxVelocity = 2;
// The target frames per second (how often do we want to update / redraw the scene)
var targetFPS = 33;
// Set the dimensions of the canvas as variables so they can be used.
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
// borders for particles on top and bottom
var borderTop = 0.01 * canvasHeight;
var borderBottom = 0.99 * canvasHeight;
// Create an image object (only need one instance)
var imageObj = new Image();
// x position of scrolling image
var imageX = 0;
var looping = false;
var totalSeconds = 0;
// Once the image has been downloaded then set the image on all of the particles
imageObj.onload = function() {
particles.forEach(function(particle) {
particle.setImage(imageObj);
});
};
// Once the callback is arranged then set the source of the image
imageObj.src = "https://image.ibb.co/fdpeJF/Smoke.png";
// A function to create a particle object.
function Particle(context) {
// Set the initial x and y positions
this.x = 0;
this.y = 0;
// Set the initial velocity
this.xVelocity = 0;
this.yVelocity = 0;
// Set the radius
this.radius = 5;
// Store the context which will be used to draw the particle
this.context = context;
// The function to draw the particle on the canvas.
this.draw = function() {
// If an image is set draw it
if (this.image) {
this.context.drawImage(this.image, this.x - 128, this.y - 128);
// If the image is being rendered do not draw the circle so break out of the draw function
return;
}
// Draw the circle as before, with the addition of using the position and the radius from this object.
this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
this.context.fillStyle = "rgba(0, 255, 255, 1)";
this.context.fill();
this.context.closePath();
};
// Update the particle.
this.update = function() {
// Update the position of the particle with the addition of the velocity.
this.x += this.xVelocity;
this.y += this.yVelocity;
// Check if has crossed the right edge
if (this.x >= canvasWidth) {
this.xVelocity = -this.xVelocity;
this.x = canvasWidth;
}
// Check if has crossed the left edge
else if (this.x <= 0) {
this.xVelocity = -this.xVelocity;
this.x = 0;
}
// Check if has crossed the bottom edge
if (this.y >= borderBottom) {
this.yVelocity = -this.yVelocity;
this.y = borderBottom;
}
// Check if has crossed the top edge
else if (this.y <= borderTop) {
this.yVelocity = -this.yVelocity;
this.y = borderTop;
}
};
// A function to set the position of the particle.
this.setPosition = function(x, y) {
this.x = x;
this.y = y;
};
// Function to set the velocity.
this.setVelocity = function(x, y) {
this.xVelocity = x;
this.yVelocity = y;
};
this.setImage = function(image) {
this.image = image;
};
}
// A function to generate a random number between 2 values
function generateRandom(min, max) {
return Math.random() * (max - min) + min;
}
// The canvas context if it is defined.
var context;
// Initialise the scene and set the context if possible
function init() {
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (canvas.getContext) {
// Set the context variable so it can be re-used
context = canvas.getContext('2d');
// Create the particles and set their initial positions and velocities
for (var i = 0; i < particleCount; ++i) {
var particle = new Particle(context);
// Set the position to be inside the canvas bounds
particle.setPosition(generateRandom(0, canvasWidth), generateRandom(borderTop, borderBottom));
// Set the initial velocity to be either random and either negative or positive
particle.setVelocity(generateRandom(-maxVelocity, maxVelocity), generateRandom(-maxVelocity, maxVelocity));
particles.push(particle);
context.clearRect(0, 0, canvas.width, canvas.height);
}
} else {
alert("Please use a modern browser");
}
}
// The function to draw the scene
function draw() {
// background image
context.globalAlpha = 1;
context.globalCompositeOperation = 'source-over';
// draw twice to cover wrap around
context.drawImage(backImg, imageX, 0, canvasWidth, canvasHeight);
context.drawImage(backImg, imageX + canvasWidth, 0, canvasWidth, canvasHeight);
context.fillStyle = "rgba(255,255,255, .5)";
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.globalAlpha = 0.75;
context.globalCompositeOperation = 'soft-light';
// Fog layer
// Go through all of the particles and draw them.
particles.forEach(function(particle) {
particle.draw();
});
}
// Update the scene
function update() {
// incrementally change image position of background to scroll left
imageX -= maxVelocity;
if (imageX < -canvasWidth) {
imageX += canvasWidth;
}
particles.forEach(function(particle) {
particle.update();
});
}
// Initialize the scene
init();
backImg = new Image();
backImg.src = 'https://image.ibb.co/cTOOdF/e2VZQY.jpg';
// If the context is set then we can draw the scene (if not then the browser does not support canvas)
if (context) {
setInterval(function() {
// Update the scene befoe drawing
update();
// Draw the scene
draw();
}, 1000 / targetFPS);
}
<canvas id="myCanvas"></canvas>
Just to add to the answer given some additional improvements to the code structure.
Use requestAnimationFrame to call render calls.
Don't expose properties of objects if not needed.
Don't use forEach iteration in time critical code. Use for loops.
Use constants where ever possible.
Comments that state the obvious are just noise in the source code making it harder to read. Limit comment to abstracts that may not be obvious to another programmer reading the code.
eg
// If an image is set draw it
if (this.image) {
Really is that comment of any use to anyone. Comments should help not degrade the readability of code.
Also the original code tried to set the global composite operations to soft-lights this is not a know operation. I corrected it to soft-light which can on some machines, be a very slow render operation. It may pay to selected another operation for machines that are slow. This can be done by simply monitoring the render time of particles and switching operation type is too slow.
A quick rewrite of the OP's code.
const particles = [];
const particleCount = 60;
const maxVelocity = 2;
var canvasWidth = innerWidth;
var canvasHeight = innerHeight;
var borderTop = 0.01 * canvasHeight;
var borderBottom = 0.99 * canvasHeight;
var ctx;
const backgroundColor = "rgba(255,255,255, .5)";
const backgroundSpeed = -0.1;
var looping = false;
var totalSeconds = 0;
var lastTime = 0;
var frameTime = (1000 / 30) - (1000 / 120); // one quater frame short to
// allow for timing error
var imageCount = 0;
const backImg = new Image();
const imageObj = new Image();
backImg.src = 'https://image.ibb.co/cTOOdF/e2VZQY.jpg';
imageObj.src = "https://image.ibb.co/fdpeJF/Smoke.png";
backImg.onload = imageObj.onload = imageLoad;
function imageLoad(){
imageCount += 1;
if(imageCount === 2){
init();
}
}
function init() {
var canvas = myCanvas;
canvas.width = innerWidth;
canvas.height = innerHeight;
ctx = canvas.getContext('2d');
for (var i = 0; i < particleCount; i += 1) {
particles.push(new Particle(ctx));
}
lastTime = performance.now();
requestAnimationFrame(mainLoop);
}
function mainLoop(time){
if(time-lastTime > frameTime){
lastTime = time;
update();
draw(time);
}
requestAnimationFrame(mainLoop);
}
const rand = (min, max) => Math.random() * (max - min) + min; // names are best short (short only without ambiguity)
function Particle(ctx) {
var x, y, xVel, yVel, radius, image;
const color = "rgba(0, 255, 255, 1)";
x = rand(0, canvasWidth),
y = rand(borderTop, borderBottom);
xVel = rand(-maxVelocity, maxVelocity);
yVel = rand(-maxVelocity, maxVelocity);
radius = 5;
image = imageObj;
this.draw = function () { ctx.drawImage(image, x - 128, y - 128) }
this.update = function () {
x += xVel;
y += yVel;
if (x >= canvasWidth) {
xVel = -xVel;
x = canvasWidth;
}
else if (x <= 0) {
xVel = -xVel;
x = 0;
}
if (y >= borderBottom) {
yVel = -yVel;
y = borderBottom;
}
else if (y <= borderTop) {
yVel = -yVel;
y = borderTop;
}
}
}
function draw(time) {
var i,x;
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
x = time * backgroundSpeed;
x = ((x % canvasWidth) + canvasWidth) % canvasWidth;
ctx.drawImage(backImg, x, 0, canvasWidth, canvasHeight);
ctx.drawImage(backImg, x - canvasWidth, 0, canvasWidth, canvasHeight);
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.globalAlpha = 0.75;
ctx.globalCompositeOperation = 'soft-light';
for(i = 0; i < particles.length; i += 1){
particles[i].draw();
}
}
function update() {
for(i = 0; i < particles.length; i += 1){
particles[i].update();
}
}
canvas {
position : absolute;
top : 0px;
left : 0px;
}
<canvas id=myCanvas></canvas>

How do I redraw the background, so it will look like my "player" moving in html5-canvas

This is my JavaScript. I have an animate function, I think this is where the redrawing background code goes. I have tried to use document.getElementById to get the id of the canvas, and give the style rule of background: white. But it didn't work. All help is appreciated!:
function initCanvas(){
var ctx = document.getElementById('my_canvas').getContext('2d');
var cW = ctx.canvas.width, cH = ctx.canvas.height;
var dist = 10;
function Player(){
this.x = 0, this.y = 0, this.w = 50, this.h = 50;
ctx.fillStyle = "orange";
this.render = function(){
ctx.fillRect(this.x, this.y, this.w, this.h);
}
}
var player = new Player();
player.x = 100;
player.y = 225;
function animate(){
//This is where I think the background redrawing should go
player.render();
}
var animateInterval = setInterval(animate, 30);
document.addEventListener('keydown', function(event) {
var key_press = String.fromCharCode(event.keyCode);
if(key_press == "W"){
player.y-=dist;
} else if(key_press == "S"){
player.y+=dist;
} else if(key_press == "A"){
player.x-=dist;
} else if(key_press == "D"){
player.x+=dist;
}
});
}
window.addEventListener('load', function(event) {
initCanvas();
});
Here are a couple things I've noticed:
You didn't declare var canvas = document.getElementById('my_canvas');
Your initCanvas() wasn't firing(It wasn't for me)
Your render() function should reset the fillStyle before it draws your character. Having the fillStyle set when initializing the Player constructor is useless(It can be overridden).
Here is what your animate() function should look like:
function animate(){
ctx.fillStyle = '#000';
ctx.fillRect(0,0,canvas.width, canvas.height);
player.render();
}
Notice how fillRect() clears the canvas before drawing the player.
I have created a working JSFiddle with the fixes here.

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.

How to draw 3d object javascript

I am making a simple JavaScript program that draws a rotated prism. I have vectors that contain x, y and z coordinates of every point and to which point they are connected. The problem I am having is I cannot find the perfect way to compare the dots in 2d. When the figure rotates, it has little, but still visible, defects and it looks like the lines become longer and shorter. I will paste the important parts of the code.
var canvas = document.getElementById("canvas-id");
canvas.width = 1200;
canvas.height = 500;
var ctx = canvas.getContext("2d");
var dx=[],dy=[],dz=[],dh=[],dgo=[],h=10,ang=10*Math.PI/360;
var pause=false;
for(var i=0;i<h/2;i++){
dx[i]=Math.cos(i/h*4*Math.PI+Math.PI/4)*70.71;
dy[i]=Math.sin(i/h*4*Math.PI+Math.PI/4)*70.71;
console.log(i/h*2*360);
dz[i]=150;
dh[i]=3;
dgo[i]=[];
dgo[i][0]=i+h/2;
dgo[i][1]=i+1;
dgo[i][2]=i-1;
dx[i+h/2]=Math.cos(i/h*4*Math.PI+Math.PI/4)*70.71;
dy[i+h/2]=Math.sin(i/h*4*Math.PI+Math.PI/4)*70.71;
dz[i+h/2]=250;
dh[i+h/2]=3;
dgo[i+h/2]=[];
dgo[i+h/2][0]=i;
dgo[i+h/2][1]=i+h/2+1;
dgo[i+h/2][2]=i+h/2-1;
if(i==h/2-1){
dgo[i][1]-=h/2;
dgo[i+h/2][1]-=h/2;
}
if(i==0){
dgo[i][2]+=h/2;
dgo[i+h/2][2]+=h/2;
}
}
window.addEventListener("mouseup", function (args) {
pause=!pause;
}, false);
function abs(a){
if(a>=0) return a;
return -a;
}
function pit(x1,y1,x2,y2){
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
function rotate(x,y,z){
for(var i=0;i<h;i++){
var m=Math.atan2(dx[i]-x,dz[i]-z)/2/Math.PI*360-90,dis=pit(dx[i],dz[i],x,z);
if(m>0) m-=360
dx[i]=x+Math.cos(abs(m)/360*2*Math.PI+ang)*dis;
dz[i]=z+Math.sin(abs(m)/360*2*Math.PI+ang)*dis;
}
}
function update() {
if(!pause)rotate(0,0,200)
setTimeout(update, 10);
}
function line(x1,y1,x2,y2){
if((x1>0 && y1>0 && x1<canvas.width && y1<canvas.height) || (x2>0 && y2>0 && x2<canvas.width && y2<canvas.height))
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = 1;
for(var i=0;i<h;i++){
for(var j=0;j<dh[i];j++){
if(dz[i]>0 && dz[dgo[i][j]]>0)
line(dx[i]/Math.sqrt(dz[i])*10+canvas.width/2,dy[i]/Math.sqrt(dz[i])*10+canvas.height/2,
dx[dgo[i][j]]/Math.sqrt(dz[dgo[i][j]])*10+canvas.width/2,dy[dgo[i][j]]/Math.sqrt(dz[dgo[i][j]])*10+canvas.height/2);
}
}
console.log(ctx.translate(0,0,10));
requestAnimationFrame(draw);
}
draw();
update();

Categories

Resources