You can't stop the loading of images, however it is possible to cancel an ordinary AJAX request (see this solution on SO). Usually images aren't loaded via AJAX for good reasons, but you can work around this by sending the image as a base64 encoded string. So you let PHP read the image and convert it to base64. This string can be sent to JS via AJAX and "directly" drawn to your canvas (solution on SO).
I really don't know if this is the best way to do this... Anyways, see if this works for you:
HTML:
<canvas id="background" width="800" height="600"></canvas>
JavaScript: (using jQuery)
function drawBackgroundImage(src) {
var image = $("<img/>").load(function(){
$("canvas#background")[0].getContext("2d").drawImage(image[0], 0, 0);
}).attr("src", src);
}
function loadImage(highres, lowres) {
var t;
var xhr = $.ajax({
type: "POST",
url: "load_image.php",
data: "image=" + highres,
success: function(imgbinary){
if (imgbinary != "") {
clearTimeout(t);
drawBackgroundImage(imgbinary);
}
}
});
t = setTimeout(function(){
xhr.abort();
drawBackgroundImage(lowres);
}, 5000);
}
loadImage("path/to/highres.png", "path/to/low_res.png");
PHP: (load_image.php)
(This uses part of a function from the PHP manual.)
<?php
$result = "";
@ob_start();
if (isset($_POST["image"])) {
$filename = $_POST["image"];
if (file_exists($filename)) {
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
$result = "data:image/".$filetype.";base64,".base64_encode($imgbinary);
}
}
@ob_end_clean();
echo $result;
?>