Created
June 8, 2018 08:38
-
-
Save junlas/149045b38e39e18210af740a7548fc58 to your computer and use it in GitHub Desktop.
截屏获取image base64字符串
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 返回 image base64 | |
getImgBase64() { | |
let sp = cc.find('Canvas/New Sprite(Splash)').getComponent(cc.Sprite); | |
let target = cc.find('Canvas'); | |
let width = 960, | |
height = 640; | |
let renderTexture = new cc.RenderTexture(width, height); | |
renderTexture.begin(); | |
target._sgNode.visit(); | |
renderTexture.end(); | |
// | |
let canvas = document.createElement('canvas'); | |
let ctx = canvas.getContext('2d'); | |
canvas.width = width; | |
canvas.height = height; | |
if (cc.renderType === cc.game.RENDERTYPE_CANVAS) { | |
let texture = renderTexture.getSprite().getTexture(); | |
let image = texture.getHtmlElementObj(); | |
ctx.drawImage(image, 0, 0); | |
} else if (cc.renderType === cc.game.RENDERTYPE_WEBGL) { | |
let buffer = gl.createFramebuffer(); | |
gl.bindFramebuffer(gl.FRAMEBUFFER, buffer); | |
let texture = renderTexture.getSprite().getTexture()._glID; | |
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); | |
let data = new Uint8Array(width * height * 4); | |
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); | |
gl.bindFramebuffer(gl.FRAMEBUFFER, null); | |
let rowBytes = width * 4; | |
for (let row = 0; row < height; row++) { | |
let srow = height - 1 - row; | |
let data2 = new Uint8ClampedArray(data.buffer, srow * width * 4, rowBytes); | |
let imageData = new ImageData(data2, width, 1); | |
ctx.putImageData(imageData, 0, row); | |
} | |
} | |
return canvas.toDataURL('image/png'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment