A common example of loading an image in JS to draw onto an HTML5 canvas is:
var canvas = $("#mycanvas")[0];
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'URL HERE';
img.onload = function() {
context.drawImage(img, 0, 0);
};
BUT how do we handle the case where the image failed to load?
e.g. when loading JSON data with JQuery there's a .fail
method for handling load failures:
$.getJSON(url)
.done(function(data, statusText, jqXHR) {
// data loaded ok
})
.fail(function(jqXHR, textStatus, errorThrown) {
// error loading data - ERROR HANDLING HERE
})
;
Great, but is there some equivalent in JS for handling image loading errors?
Is there some other event similar to .onload
but which triggers on failure to load? Or does .onload
trigger in either case?
Similar problem when loading a video into a video tag:
var videoElement = $("#myvideo")[0];
$("#mvideo").append("<source src='URL HERE' type='TYPE STRING HERE'>");
videoElement.load();
videoElement.play();
i.e. how to we detect a load failure so we can add error handling code?