JS Canvas Snaps

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的图片传输的字符串比较大,效率比较低,特别当图片很大的时候。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值