Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q: HTML5 Canvas change background color

I am just wondering is it possible to change Canvas color from function call? I have this code with circle inside I would like to change outside color (background):

var canvads = document.getElementById('canvas')
var context = canvas.getContext('2d');

function circle() {
  var centerX = 0;
  var centerY = 0;
  var radius = 78;
  context.clearRect(0, 0, window.innerWidth,window.innerHeight);

  context.fillStyle = 'rgba(0,0,0,0.5)';
  context.fillRect(0,0,window.innerWidth,window.innerHeight);

  context.translate(canvas.width / 2, canvas.height / 2);

  context.scale(1.5, 2);

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 5 * Math.PI, false);

  context.lineWidth = 5;
  context.stroke();

  context.fillStyle = 'rgba(0,0,0,1)';

  context.globalCompositeOperation = 'destination-out';
  context.fill();

  context.globalCompositeOperation = 'source-over';
}

function change_color() {
  context.fillStyle = 'rgba(0,255,0,1)';
  context.fill();
}

circle()

JsFiddle

like image 882
user2808421 Avatar asked Dec 06 '22 14:12

user2808421


1 Answers

What you need is to change approach a little - although it's possible to some extent to "fill background", the main way canvas works is constant redrawing of the whole image. In HTML games, it's done X times per second, but in smaller projects, it often should be done after each action. So, in your case, something like this should probably do the trick: FIDDLE

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

function initCanvas() {
  context.clearRect(0, 0, window.innerWidth,window.innerHeight);

  context.fillStyle = 'rgba(0,0,0,0.5)';
  context.fillRect(0,0,window.innerWidth,window.innerHeight);
}

function circle() {
  var centerX = 0;
  var centerY = 0;
  var radius = 78;

  context.save()
  context.translate(canvas.width / 2, canvas.height / 2);

  context.scale(1.5, 2);

  // define the arc path
  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 5 * Math.PI, false);

  // stroke it
  context.lineWidth = 5;
  context.stroke();

  // make alpha solid (the color doesn't matter)
  context.fillStyle = 'rgba(0,0,0,1)';

  // change composite mode and fill
  context.globalCompositeOperation = 'destination-out';
  context.fill();
  context.restore()

  // reset composite mode to default
}

function changeColor() {
  context.fillStyle = 'rgba(0,255,0,1)';
  context.fillRect(0,0,window.innerWidth,window.innerHeight);

  circle()
}

initCanvas()
circle()
document.querySelector('#but').addEventListener('click',changeColor)

And pay attention to save/restore, especially after transforms/rotating. Also, fixed onclick.

like image 51
Michał Sałaciński Avatar answered Dec 19 '22 22:12

Michał Sałaciński