Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Trying to draw a canvas with two "players" but after adding more code it doesn't work?

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!