HTML5 Game - Loading the canvas with a data URL via ajax

Introduction

The following code makes an Ajax call to get the data URL from a text file.

Then use the URL to draw the image on the canvas.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <script>
         function loadCanvas(dataURL){ 
            let canvas = document.getElementById("myCanvas"); 
            let context = canvas.getContext("2d"); 
             /*from   ww w  .ja v a 2  s. co  m*/
            // load image from data url 
            let imageObj = new Image(); 
            imageObj.onload = function(){ 
                context.drawImage(this, 0, 0); 
            }; 
             
            imageObj.src = dataURL; 
         } 
         window.onload = function(){ 
            // make ajax call to get image data url 
            let request = new XMLHttpRequest(); 
            request.open("GET", "dataURL.txt", true); 
            request.onreadystatechange = function(){ 
                if (request.readyState == 4) {  
                    if (request.status == 200) { // successful response 
                        loadCanvas(request.responseText); 
                    } 
                } 
            }; 
            request.send(null); 
         }; 
         
        </script>
    </head>
    <body>
         <canvas id="myCanvas" width="578" height="200"> 
         </canvas> 
    </body>
</html>

Note

To get the image data URL from a web server, we can set up an AJAX call (Asynchronous JavaScript and XML).

Related Topic