JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas" width="400" height="400" >
Your browser does not support the HTML5 canvas tag.
</canvas>
CSS
canvas { border: 1px solid black; }
JavaScript
// Basic Image Loading and Drawing
//
// Illustrates both "naive" and "smart" styles.
"use strict";
/* jshint browser: true, devel: true, globalstrict: true */
// Uncomment the following to see the actual result...
STOP;
/*
Stay within this 72 character margin, to keep your code easily readable
1 2 3 4 5 6 7
123456789012345678901234567890123456789012345678901234567890123456789012
*/
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// NAIVE
// =====
//
// This "naive" approach won't work in general,
// although you might get lucky if the image is in-cache
//
//
// 1. Create an "Image" object
//
var naiveImage = new Image();
//
// 2. Set the "src" property.
// This implicitly tells the browser to load the requested image.
//
naiveImage.src = "http://placekitten.com/100/100";
//
// 3. Use drawImage to blit it onto the canvas
//
console.log("about to draw naiveImage");
console.log("width =", naiveImage.width);
ctx.drawImage(naiveImage, 10, 10);
console.log("finished drawing naiveImage.. assuming it loaded in time.");
console.log("");
// SMART
// =====
//
// The "smart" approach should work, assuming the load
// actually succeeds, but the timing of the onload call,
// relative to everything else, becomes unpredictable.
//
//
// 1. Create an "Image" object
//
var smartImage = new Image();
//
// 2. Set the "onload" callback function.
// This will get called in reaction to the image-load "event"
//
smartImage.onload = function () {
console.log("entering: smartImage.onload()");
console.log("about to draw smartImage");
console.log("width =", smartImage.width);
ctx.drawImage(smartImage, 200, 200);
console.log("finished drawing smartImage");
console.log("");
};
//
// 3. Set the "src" property... *after* setting the onload handler.
// This implicitly tells the browser to load the requested image.
// But we need to set "onload" first, because...