你得到的gl.readPixels
是位图数据。我使用Jimp库将数据转换为不同的格式,然后从中获取 base64 图像字符串。
NodeJS 代码
var Jimp = require("jimp")
//Create context
var width = 50
var height = 50
var gl = require('gl')(width, height, { preserveDrawingBuffer: true })
//Clear screen to red
gl.clearColor(1, 0, 0, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
// get bitmap data
var bitmapData = new Uint8Array(width * height * 4)
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, bitmapData)
// use Jimp library to create an image with a specific mime type
var image = new Jimp(width, height, function (err, image) {
// assign the bitmap as data for the image
image.bitmap.data = bitmapData
// generate base64
image.getBase64("image/png", function (error, str) {
// result
console.log(str)
})
})
在浏览器中测试它是否适合您(JS 代码):
var base64Img = "" // TODO paste the result from NodeJS
document.body.innerHTML = ""
document.write('<img src="' + base64Img + '"/>');