<img src="x.jpg" id=i>
是否可以使用像getElementById(&#34; i&#34;)这样的东西来访问二进制文件。某些东西?
答案 0 :(得分:1)
来自MDN demo:
它们在下面的示例中显示了如何使用包含在Promise中的XHR请求来获取图像。 (你真的不需要诺言部分,但很酷)。
只需确保图片位于运行此代码的同一域中,或使用JSONP打包。
对于您的问题,您可以迭代页面上的所有图片,并使用imgLoad
运行src
函数来获取数据。我想不出一种方法来访问已经通过浏览器自己的机制下载的图像数据(src ='...')
function imgLoad(url) {
// Create new promise with the Promise() constructor;
// This has as its argument a function
// with two parameters, resolve and reject
return new Promise(function(resolve, reject) {
// Standard XHR to load an image
var request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = 'blob';
// When the request loads, check whether it was successful
request.onload = function() {
if (request.status === 200) {
// If successful, resolve the promise by passing back the request response
resolve(request.response);
} else {
// If it fails, reject the promise with a error message
reject(Error('Error code:' + request.statusText));
}
};
request.onerror = function() {
// Also deal with the case when the entire request fails to begin with
// This is probably a network error, so reject the promise with a message
reject(Error('There was a network error.'));
};
// Send the request
request.send();
});
}
// Get a reference to the body element, and create a new image object
var body = document.querySelector('body');
var myImage = new Image();
// Call the function with the URL we want to load, but then chain the
// promise then() method on to the end of it. This contains two callbacks
imgLoad('myLittleVader.jpg')
.then(function(response) {
// The first runs when the promise resolves, with the request.reponse
// specified within the resolve() method.
var imageURL = window.URL.createObjectURL(response);
myImage.src = imageURL;
body.appendChild(myImage);
// The second runs when the promise
// is rejected, and logs the Error specified with the reject() method.
},
function(Error) {
console.log(Error);
});