Reputation: 98
I'm really frustrated right now, JS never works for me. I don't know what little mistake I made this time, I'll be grateful if you point it out. I don't want an animation or anything, I'd be happy if someone tells me the error.
window.onload = function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth();
canvas.height = window.innerHeight();
var ship = function() {
this.x = canvas.width/2;
this.y = canvas.height/2;
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;
this.show = function() {
//background
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(0,0,canvas.width,canvas.height);
//update
this.velocityX += this.accelerationX;
this.velocityY += this.accelerationY;
this.x += this.velocityX;
this.y += this.velocityY;
//draw
context.save();
context.translate(this.x,this.y) ;
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(0,0,20,30);
context.restore();
};
};
var myship = new ship();
myship.show();
};
Upvotes: 0
Views: 1293
Reputation: 32859
You have two issues ...
1. innerWidth / innerHeight
isn't a method / function, it's a property of the window
object. so, the correct form would be window.innerWidth / window.innerHeight
2. You aren't able to view the ship
object, as you set both the background's and ship's fillStyle
to black. so, either change fillStyle
of the background or the ship to a different color.
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ship = function() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;
this.show = function() {
//background
context.fillStyle = 'rgb(255,255,255)';
context.fillRect(0, 0, canvas.width, canvas.height);
//update
this.velocityX += this.accelerationX;
this.velocityY += this.accelerationY;
this.x += this.velocityX;
this.y += this.velocityY;
//draw ship
context.save();
context.translate(this.x, this.y);
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(0, 0, 20, 30);
context.restore();
};
};
var myship = new ship();
myship.show();
#canvas {
border: 1px solid black;
}
<canvas id="canvas" width="300" height="300"></canvas>
Upvotes: 2