Home > Software engineering >  Trying to draw a canvas with two "players" but after adding more code it doesn't work
Trying to draw a canvas with two "players" but after adding more code it doesn't work

Time:06-24

I'm trying to draw a canvas with two blocks in it, which I'm going to turn into two players/characters. However after the first few lines of code, if I add anything else to it then nothing loads anymore. I am just starting to learn JavaScript so I have no clue why it isn't working.

var canvas = document.getElementById('canvas');
var c = canvas.getContext("2d");



canvas.width = 1000 
canvas.height = 500 

c.fillRect(50, 50, canvas.width, canvas.height)


// If i try add the code below then everything disappears. 
/*
 class Sprite {
    constructor(position) {
this.position = position

    }

    draw() {
     c.fillStyle='red'
     c.fillRect(this.position.x, this.position.y, 50, 150)

    }
}

const player = new Sprite( {
        x: 0,
        y: 0
    } )

player.draw()

const enemy = new Sprite(
    {
        x: 400,
        y: 100
    }
)

enemy.draw()

console.log(player) */
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>STREET FIGHTER</title>
 </head>

<body>
 
  <canvas id="canvas"></canvas>
  <script src="index.js"></script>

</body>

</html>

CodePudding user response:

Works fine for me...
I see nothing that will cause the behavior you describe
See code below, I removed the comment on your class:

var canvas = document.getElementById('canvas');
var c = canvas.getContext("2d");
canvas.width = canvas.height = 140

c.fillRect(50, 30, canvas.width, canvas.height)


class Sprite {
  constructor(rect, color) {
    this.rect = rect
    this.color = color
  }

  draw() {
    c.fillStyle = this.color
    c.fillRect(this.rect.x, this.rect.y, this.rect.w, this.rect.h)
  }
}

const player = new Sprite({ x: 15, y: 10, w:9, h:9 }, "red")
player.draw()

const enemy = new Sprite({ x: 90, y: 35, w:20, h:10}, "cyan")
enemy.draw()

console.log(player)
<canvas id="canvas"></canvas>

I change a bit the parameters in the constructor but nothing that will affect your original code

  • Related