您无法停止加载图像,但可以取消普通的AJAX请求(see this solution on SO)。通常情况下,图像不会通过AJAX加载,但您可以通过将图像作为base64编码字符串发送来解决此问题。所以你让PHP读取图像并将其转换为base64。该字符串可以通过AJAX发送给JS,并“直接”绘制到您的画布上(solution on SO)。
我真的不知道这是做到这一点的最好方式......不管怎么说,看看这对你的作品:
HTML:
<canvas id="background" width="800" height="600"></canvas>
的JavaScript :(使用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)
(该使用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;
?>
检查http://stackoverflow.com/questions/930237/javascript-cancel-stop-image-requests – 2012-07-26 15:33:38
我不能使用window.stop,因为我加载了更多的对象异步。 – eqiproo 2012-07-26 15:51:02
坏消息〜我会找到另一个〜 – 2012-07-26 15:55:44