To load the canvas with a data URL, we can extend the previous recipe by creating an image
object with the data URL and then drawing it on the canvas using our good friend drawImage()
. In this recipe, we'll make a simple Ajax call to get the data URL from a text file and then use the URL to draw the image on the canvas. In the real world of course, you'll probably be fetching the image data URL from local storage or by calling a data service.
Follow these steps to load a canvas drawing with a data URL:
Define the
loadCanvas()
function which takes a data URL as input, defines a canvas context, creates a new image using the data URL, and then draws the image onto the canvas once it has loaded:function loadCanvas(dataURL){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); // load image from data url var imageObj = new Image(); imageObj.onload = function(){ context.drawImage...