Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  23] [ 3]  / answers: 1 / hits: 28430  / 7 Years ago, tue, may 23, 2017, 12:00:00

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


More From » html

 Answers
16

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.


[#57692] Friday, May 19, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;