Javascript examples for Canvas:image
Fading a loaded image into Canvas with drawImage
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> <style id="compiled-css" type="text/css"> body {//from ww w. ja v a2 s . c om background-color: ivory; } canvas { border:1px solid red; } </style> <script type="text/javascript"> $(window).load(function(){ $("#fade").hide(); var imageURLs = []; // put the paths to your images here var imagesOK = 0; var imgs = []; imageURLs.push("https://www.java2s.com/style/demo/InternetExplorer.png"); imageURLs.push("https://www.java2s.com/style/demo/InternetExplorer.png"); imageURLs.push("https://www.java2s.com/style/demo/Safari.png"); imageURLs.push("https://www.java2s.com/style/demo/InternetExplorer.png"); loadAllImages(); // function loadAllImages() { for (var i = 0; i < imageURLs.length; i++) { var img = new Image(); imgs.push(img); img.onload = function () { imagesOK++; if (imagesOK >= imageURLs.length) { $("#fade").show(); ctx.drawImage(imgs[0], 0, 0); } }; img.onerror = function () { console.log("image load failed"); } img.crossOrigin = "anonymous"; img.src = imageURLs[i]; } } var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var fadeOutIndex = imgs.length - 1; var fadeInIndex = 0; var fadePct = 0; function animateFade() { if (fadePct > 100) { return; } requestAnimationFrame(animateFade); // ctx.clearRect(0,0,canvas.width,canvas.height); draw(imgs[fadeInIndex], fadePct / 100); draw(imgs[fadeOutIndex], (1 - fadePct / 100)); fadePct++; } function draw(img, opacity) { ctx.save(); ctx.globalAlpha = opacity; ctx.drawImage(img, 0, 0); ctx.restore(); } $("#fade").click(function () { fadePct = 0; if (++fadeOutIndex == imgs.length) { fadeOutIndex = 0; } if (++fadeInIndex == imgs.length) { fadeInIndex = 0; } animateFade(); }); }); </script> </head> <body> <button id="fade">Fade to next Image</button> <br> <canvas id="canvas" width="204" height="204"></canvas> <br> </body> </html>