I am trying to create a 2d platformer, and the code is the base of it.
For some unknown reason, my final function draw mixes the other functions\' properties (especiall
The problem is that you first draw the shape and after that you set the fill and the stroke. Doing so you set the fill and stroke for the next shape.
In my code I'm using ctx.translate(0,-400)
because otherwise the canvas would have been too large. Remove this line when setting your canvas size.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//setting the canvas size
canvas.width = 400;
canvas.height = 200;
ctx.translate(0,-400);
function Shooter() {
this.x = 100;
this.y = 500;
this.size = 50;
this.color = "blue";
this.borderColor = "black";
this.borderWidth = 5;
this.draw = function() {
// first set the colors for this shape
ctx.fillStyle = this.color;
ctx.strokeStyle = this.borderColor;
ctx.lineWidth = this.borderWidth;
// then fill and stroke the shape
ctx.fillRect(this.x, this.y, this.size, this.size);
ctx.strokeRect(this.x, this.y, this.size, this.size);
}
}
function Gun() {
this.x = sh.x + sh.size / 2 + 10;
this.y = sh.y + sh.size / 2;
this.color = "grey";
this.borderColor = "brown";
this.borderWidth = 1;
this.width = 20;
this.height = 10;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.strokeStyle = this.borderColor;
ctx.lineWidth = this.borderWidth;
ctx.fillRect(this.x,this.y,this.width,this.height); ctx.strokeRect(this.x,this.y,this.width,this.height);
}
}
function Bullet() {
this.x = sh.x + sh.size * 2;
this.y = sh.y + sh.size / 2;
this.color = "orange";
this.radius = 5;
this.vx = 20;
this.borderColor = "green";
this.borderWidth = 2;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.strokeStyle = this.borderColor;
ctx.lineWidth = this.borderWidth;
ctx.fill();
ctx.stroke();
}
}
var sh = new Shooter();
var g = new Gun();
var b = new Bullet();
function draw() {
sh.draw();
g.draw();
b.draw();
requestAnimationFrame(draw);
}
draw();
canvas{border:1px solid}