上代码:
<body>
<canvas width="300" height="300" id="cvs"></canvas>
<script>
const cvs = document.getElementById('cvs');
const ctx = cvs.getContext('2d');
function getPic() {
const xhr = new XMLHttpRequest();
xhr.open('get', 'http://localhost:1234/pic.png');
xhr.responseType = 'blob';
xhr.onload = function () {
if (xhr.status === 200) {
createImageBitmap(xhr.response).then(result => {
ctx.drawImage(result, 0, 0);
})
}
}
xhr.send();
}
getPic();
</script>
</body>
流程是:
ctx.drawImage接口,第一个参数可以是
显然,只有ImageBitmap可能符合要求。
ImageBitmap介绍:
提供了createImageBitmap接口,是一个工厂方法,可以从多种源获得imageBitmap
多种源包括:
里面包含了blob的源,正好对应xmlhttprequest.responseType的blob
所以最终关键点就在:
xhr.responseType = 'blob';
这一步了
它让浏览器将服务器buffer数据转换成blob。
类型链:
createImageBitmap(xhr.response/* blob */)
.then(result/* imageBitmap */ => {
ctx.drawImage(result, 0, 0);
})