Igal
Igal

Reputation: 6093

Drawing 2 shapes in different colors on canvas

I have a function draw in which I try to draw a black circle and a yellow rectangle on a canvas:

function draw() {
  context.clearRect(0, 0, window.innerWidth, window.innerHeight);
  context.fillStyle = '000000';
  context.beginPath();
  context.arc(ballx, bally, radius, 0, Math.PI * 2);
  context.fill();
  context.fillStyle = '#F7CA18';
  context.fillRect(0, 0, 50, 5);
}

The function is being called with setInterval every 40 ms (I need it to create a certain circle animation later). For some reason both shapes are drawn yellow.

I tried to close the Path after context.fill() and to reopen it again before the rectangle, tried to define the black fill again after fillRect, tried a few more things, but no success.

Any idea how to fix it?

Upvotes: 0

Views: 446

Answers (1)

dizel3d
dizel3d

Reputation: 3669

You have a typo in black color (missed "#"):

context.fillStyle = '#000000';

Working example:

function draw(context, ballx, bally, radius) {
  context.clearRect(0, 0, window.innerWidth, window.innerHeight);
  context.fillStyle = '#000000';
  context.beginPath();
  context.arc(ballx, bally, radius, 0, Math.PI * 2);
  context.fill();
  context.fillStyle = '#F7CA18';
  context.fillRect(0, 0, 50, 5);
}

var i = 50;
setInterval(function() {
    draw(document.getElementById('canvas').getContext('2d'), 50 + i++, 50, 50);
}, 40);
<canvas id="canvas" />

Upvotes: 1

Related Questions