JavaScript
x
40
40
1
class Entity {
2
constructor(name, type = 'player') {
3
this.name = name,
4
this.type = type
5
}
6
newObject(name, pvals) {
7
this[name] = {}
8
if (pvals) {
9
for (var i = 0; i < pvals.length; i += 2) {
10
this[name][pvals[i]] = pvals[i + 1]
11
}
12
}
13
}
14
}
15
16
const canvas = document.querySelector('canvas')
17
const ctx = canvas.getContext('2d')
18
19
canvas.height = window.innerHeight - 20
20
canvas.width = window.innerWidth
21
22
var frame = new Entity('frame', 'game-object')
23
var button = new Entity('button', 'player-component')
24
25
const radius = 70
26
var speed = 3
27
28
frame.newObject('$', 'r', radius)
29
button.newObject('$', 'r', radius / 3)
30
31
function updateFrame() {
32
ctx.fillStyle = 'black'
33
ctx.arc((canvas.width / 2), (canvas.height / 2), frame.$.r, 0, Math.PI * 2)
34
ctx.fill()
35
ctx.fillStyle = 'red'
36
ctx.arc((canvas.width / 2), (canvas.height / 2), button.$.r, 0, Math.PI * 2)
37
ctx.fill()
38
}
39
40
updateFrame()
JavaScript
1
1
1
<canvas></canvas>
As far as I know it should print big black circle in the middle of the canvas and on top of that a red small circle. But it just prints a big red circle. I just can’t figure it out.
Advertisement
Answer
Just like @Teemu points out in the comment “Begin the paths” you must use the ctx.beginPath()
between your arcs when you are changing colors
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath#examples
I simplified a lot of your code to show just the problem, you should do the same when you are troubleshooting class Entity
was just a distraction and we can reproduce without it
JavaScript
1
12
12
1
const canvas = document.querySelector('canvas')
2
const ctx = canvas.getContext('2d')
3
4
ctx.beginPath()
5
ctx.fillStyle = 'black'
6
ctx.arc(50, 50, 20, 0, Math.PI * 2)
7
ctx.fill()
8
9
ctx.beginPath()
10
ctx.fillStyle = 'red'
11
ctx.arc(50, 50, 10, 0, Math.PI * 2)
12
ctx.fill()
JavaScript
1
1
1
<canvas></canvas>