Reputation: 13
I'm trying to do a simple fade in fade out effect to a rectangle in Canvas by editing the string rgba. I tried subtracting and adding to an opacity value and then setting the fillStyle function but so far it only seems to fade in very quickly. Any help will be appreciated.
var ctx = cv.getContext('2d');
function fadeOutRectangle() {
var opacity = 1,
factor = 1,
increment = .01;
var steps = 50;
ctx.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')';
ctx.fillRect(10, 10, 300, 300);
interval = setInterval(function() {
if(opacity >= 1) {
factor = -1
}
else if(opacity <= 0) {
factor = 1 ;
}
opacity += factor *increment;
console.log("opacity",opacity);
ctx.fillStyle = 'rgba(255, 255, 200, ' + opacity + ')';
ctx.fillRect(20,20,150,100);
}, 1000/steps);
}
fadeOutRectangle();
Here's the jfiddle as well:
https://jsfiddle.net/dpxjfpgn/
Upvotes: 1
Views: 2754
Reputation: 15604
var ctx = cv.getContext('2d');
var opacity = 1,
factor = 1,
increment = .01;
var steps = 50, action = 'decrease';
function fadeOutRectangle() {
var rectWidth = 300;
var rectHeight = 300;
interval = setInterval(function() {
if (action == 'decrease') {
rectWidth -= 1;
if (rectWidth < 0) {
action = 'increase'
}
} else {
rectWidth += 1;
if (rectWidth > 300) {
action = 'decrease'
}
}
if (opacity >= 1) {
factor = -1
// clearInterval(interval)
} else if (opacity <= 0) {
factor = 1;
}
opacity += factor * increment;
// ctx.rect(20,20,150,100);
//console.log(ctx.fillStyle)
ctx.clearRect(0, 0, cv.width, cv.height);
ctx.beginPath();
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.fillRect(0, 0, 400, 400);
ctx.fill();
ctx.fillStyle = 'rgba(255, 255, 200, ' + opacity + ')';
ctx.fillRect(20, 20, rectWidth, 100);
//ctx.fill();
// if(i === steps) {
// clearInterval(interval);
// }
}, 1000/steps);
// clearInterval(interval)
}
fadeOutRectangle();
<canvas width="400" height="400" id="cv"></canvas>
clear the canvas using clearRect(). and then redraw. to fadein increase the width of rectangle, to fadeout decrease the width of rectangle.
Upvotes: 2