ajax的返回數據的類型有五中,,在研究three的loader的時候,突然發現ajax返回的數據還有arrayBuffer數據類型,以前我只知道返回文本,,於是我查閱資料,總結了一下,,以下是我的總結:
responseType的值如下五中:
《1》“ ”和 "text" 字符創(默認)
《2》“arraybuffer” ArrayBuffer 對象 二進制數據
《3》 “blob” blob 對象 (經常用於fileReader對象讀取文件的值)
《4》 “document” document 對象
《5》 “json” json對象
對於字符串的我們已經經常用了,,這節我們講解arraybuffer: 實現three的loader的原理,這裏以TGALoader爲例:
// content[ offset ++ ] | content[ offset ++ ] << 8, 位運算 <<的優先級高於 | ,
// 運算過程 192 | 3 << 8 ===》 192 | 768 , 3<<8 === 3 *Math.pow(2,8);
var
offset =
0,
header = {
id_length:
content[ offset ++ ],
colormap_type:
content[ offset ++ ],
image_type:
content[ offset ++ ],
colormap_index:
content[ offset ++ ] | content[ offset ++ ] << 8,
colormap_length:
content[ offset ++ ] | content[ offset ++ ] << 8,
colormap_size:
content[ offset ++ ],
origin:
[
content[ offset ++ ] | content[ offset ++ ] <<
8,
content[ offset ++ ] | content[ offset ++ ] <<
8
],
width:
content[ offset ++ ] | content[ offset ++ ] << 8,
height:
content[ offset ++ ] | content[ offset ++ ] << 8,
pixel_size:
content[ offset ++ ],
flags:
content[ offset ++ ]
};
var
canvas =
document.createElement("canvas");
canvas.width
= header.width;
canvas.height
= header.height;
var
ctx = canvas.getContext("2d");
var
imageData = ctx.createImageData(header.width,header.height);
// 將讀取的image數據賦值給imageData
var
width = header.width;
var
i =0;
pixel_size
= header.pixel_size
>>
3;
pixel_total
= header.width
* header.height
*
pixel_size;
//arraybuffer的截取方法返回一個新的arraybuffer
var
image = content.subarray(offset);
for
(
var
y =
0;
y !== header.height;
y +=
1
) {
for
(
var
x =
0;
x !== width;
x +=
1,
i +=
4
) {
imageData.data[
( x + width * y ) * 4
+
2
] = image[ i +
0
];
imageData.data[
( x + width * y ) * 4
+
1
] = image[ i +
1
];
imageData.data[
( x + width * y ) * 4
+
0
] = image[ i +
2
];
imageData.data[
( x + width * y ) * 4
+
3
] = image[ i +
3
];
}
}
ctx.putImageData(
imageData,
0,
0
);
document.body.appendChild(canvas);
希望對大家有用,,喜歡的話,請關注我!!!!