1. 2D Context:
toDataURL:返回的是一串Base64编码的URL
var tempCanvas = document.createElement('canvas');
var tempCtx = tempCanvas.getContext('2d');
var imageData = tempCanvas.toDataURL("image/png");
var image = new Image();
image.src = imageData;
2. 3D Context - toDataURL
preserveDrawingBuffer: true - 避免画完清空buffer数据,会有性能问题;
var tempCanvas = document.createElement('canvas');
var tempCtx = tempCanvas.getContext('experimental-webgl', {preserveDrawingBuffer: true}) || tempCanvas.getContext('webgl'), {preserveDrawingBuffer: true};
var imageData = tempCanvas.toDataURL("image/png");
var image = new Image();
image.src = imageData;
3. 3D Context - readPixels
注:readPixels读出来的数组只是rgba数据,没有Image的header,无法直接写入Image.src,需要自己手写header;
var tempCanvas = document.createElement('canvas');
tempCanvas.x = tempCanvas.y = 0;
tempCanvas.width = width;
tempCanvas.height = height;
var tempCtx = tempCanvas.getContext('2d');
var data = tempCtx.createImageData(width, height);
var buffer = new Uint8Array(width*height*4);
gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
var w=width*4, h=height;
for (var i=0, maxI=h/2; i<maxI; ++i) {
for (var j=0, maxJ=w; j<maxJ; ++j) {
var index1 = i * w + j;
var index2 = (h-i-1) * w + j;
data.data[index1] = buffer[index2];
data.data[index2] = buffer[index1];
}
}
tempCtx.putImageData(data, 0, 0);
return tempCanvas.toDataURL("image/png");
4. use canvas2DContext draw a WebGL Canvas
preserveDrawingBuffer: true
function getSnapshotData2(gl, canvas, x, y, width, height) {
var tempCanvas = document.createElement('canvas');
tempCanvas.x = tempCanvas.y = 0;
tempCanvas.width = width;
tempCanvas.height = height;
var tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(canvas, 0, 0)
return tempCanvas.toDataURL("image/png");
}
5. preserveDrawingBuffer: false 在draw的函数里处理buffer数据,可以避免展现后清空Buffer的问题;
6. 使用frameBuffer:
var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE) {
var pixels = new Uint8Array(width * height * 4);
gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
}
数组可以不画出来,仅仅是为了得到canvas的2D图片;
1.Image使用URL加载,可以利用浏览器的缓存,加载base64编码的图片不能缓存。
2.使用base64的图片传输的字符串比较大,效率比较低,特别当图片很大的时候。