To transition a new image onto a canvas, start by painting it with low opacity, then repaint it with increasing opacity until it is nearly fully visible. Set the canvas context’s globalAlpha before drawing. section 34.2
function draw(img, alpha=1) {
const gal = document.getElementById('gallery');
const ctx = gal.getContext('2d');
ctx.globalAlpha = alpha;
ctx.drawImage(img,
0, 0, img.width, img.height,
0, 0, gal.width, gal.height
);
}
Pass alpha to the drawing function and apply it through the canvas context before painting. section 34.2
function fadeIn(image, alpha) {
draw(image, alpha);
if (alpha >= .99) { 1
// we are done
} else {
alpha += (1-alpha)/24; 2
window.requestAnimationFrame(() => fadeIn(image, alpha)); 3
}
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":2,\"ch\":65},{\"line\":2,\"ch\":66}],[{\"line\":5,\"ch\":14},{\"line\":5,\"ch\":15}],[{\"line\":5,\"ch\":23},{\"line\":5,\"ch\":24}],[{\"line\":6,\"ch\":65},{\"line\":6,\"ch\":66}]]"}
!@%STYLE%@!
Draw each frame, increase alpha by a fraction of the remaining opacity, and schedule the next frame until alpha reaches .99. section 34.2
function fade(image) {
return new Promise(resolve => { 1
function fadeIn(alpha) { 2
draw(image, alpha); 3
if (alpha >= .99) {
resolve(); 4
} else {
alpha += (1-alpha)/24; 5
window.requestAnimationFrame(() => fadeIn(alpha)); 5
}
}
fadeIn(0.1); 6
});
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":62},{\"line\":1,\"ch\":63}],[{\"line\":7,\"ch\":18},{\"line\":7,\"ch\":19}],[{\"line\":11,\"ch\":13},{\"line\":11,\"ch\":14}],[{\"line\":2,\"ch\":62},{\"line\":2,\"ch\":63}],[{\"line\":7,\"ch\":27},{\"line\":7,\"ch\":28}],[{\"line\":3,\"ch\":62},{\"line\":3,\"ch\":63}],[{\"line\":5,\"ch\":62},{\"line\":5,\"ch\":63}],[{\"line\":7,\"ch\":28},{\"line\":7,\"ch\":29}],[{\"line\":7,\"ch\":62},{\"line\":7,\"ch\":63}],[{\"line\":8,\"ch\":62},{\"line\":8,\"ch\":63}],[{\"line\":7,\"ch\":62},{\"line\":7,\"ch\":63}],[{\"line\":8,\"ch\":62},{\"line\":8,\"ch\":63}],[{\"line\":11,\"ch\":62},{\"line\":11,\"ch\":63}]]"}
!@%STYLE%@!
Resolve a promise when the fade completes so callers can wait for the animation. section 34.2

