phaser/src/renderer/snapshot/WebGLSnapshot.js

82 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-02-12 16:01:20 +00:00
/**
* @author Richard Davey <rich@photonstorm.com>
2019-01-15 16:20:22 +00:00
* @copyright 2019 Photon Storm Ltd.
2018-02-12 16:01:20 +00:00
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
2019-01-25 10:01:53 +00:00
var GetFastValue = require('../../utils/object/GetFastValue');
2018-02-09 13:46:04 +00:00
/**
* Takes a snapshot of the current frame displayed by a WebGL canvas.
2018-02-09 13:46:04 +00:00
*
* @function Phaser.Renderer.Snapshot.WebGL
* @since 3.0.0
*
* @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of.
* @param {string} [type='image/png'] - The format of the returned image.
* @param {number} [encoderOptions=0.92] - The image quality, between 0 and 1, for image formats which use lossy compression (such as `image/jpeg`).
2018-02-09 13:46:04 +00:00
*
* @return {HTMLImageElement} A new image which contains a snapshot of the canvas's contents.
2018-02-09 13:46:04 +00:00
*/
2019-01-25 10:01:53 +00:00
var WebGLSnapshot = function (sourceCanvas, snapshotConfig)
2017-05-16 19:15:01 +00:00
{
2019-01-25 10:01:53 +00:00
var type = GetFastValue(snapshotConfig, 'type', 'image/png');
var encoderOptions = GetFastValue(snapshotConfig, 'encoder', 0.92);
var x = GetFastValue(snapshotConfig, 'x', 0);
var y = GetFastValue(snapshotConfig, 'y', 0);
var getPixel = GetFastValue(snapshotConfig, 'getPixel', false);
var gl = sourceCanvas.getContext('experimental-webgl');
2017-05-16 19:15:01 +00:00
2019-01-25 10:01:53 +00:00
if (getPixel)
{
var pixel = new Uint8Array(4);
2019-01-25 10:01:53 +00:00
gl.readPixels(x, gl.drawingBufferHeight - y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
2019-01-25 10:01:53 +00:00
return pixel;
}
else
2017-05-16 19:15:01 +00:00
{
2019-01-25 10:01:53 +00:00
var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
// CanvasPool?
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imageData;
canvas.width = gl.drawingBufferWidth;
canvas.height = gl.drawingBufferHeight;
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
for (var y = 0; y < canvas.height; y += 1)
2017-05-16 19:15:01 +00:00
{
2019-01-25 10:01:53 +00:00
for (var x = 0; x < canvas.width; x += 1)
{
var si = ((canvas.height - y) * canvas.width + x) * 4;
var di = (y * canvas.width + x) * 4;
data[di + 0] = pixels[si + 0];
data[di + 1] = pixels[si + 1];
data[di + 2] = pixels[si + 2];
data[di + 3] = pixels[si + 3];
}
2017-05-16 19:15:01 +00:00
}
2019-01-25 10:01:53 +00:00
ctx.putImageData(imageData, 0, 0);
var src = canvas.toDataURL(type, encoderOptions);
var image = new Image();
image.src = src;
return image;
2017-05-16 19:15:01 +00:00
}
};
module.exports = WebGLSnapshot;