Skip to content

Instantly share code, notes, and snippets.

@tomlarkworthy
Last active February 23, 2021 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomlarkworthy/50446fd71a738f3bbeeec165324571e8 to your computer and use it in GitHub Desktop.
Save tomlarkworthy/50446fd71a738f3bbeeec165324571e8 to your computer and use it in GitHub Desktop.
const puppeteer = require('puppeteer');
let page;
async function getBrowserPage() {
// Launch headless Chrome. Turn off sandbox so Chrome can run under root.
const browser = await puppeteer.launch({args: [
'--no-sandbox'
]});
return browser.newPage();
}
exports.screenshot_example = async (req, res) => {
if (!page) {
page = await getBrowserPage();
}
function scrapeForConsoleMessage(message) {
return new Promise(function consoleListener(resolve, err) {
page.on('console', msg => {
// Turn on debugging with &debug in the request URL
// All unity output is then logged in stackdriver
if (req.query.debug) console.log(msg.text());
if (msg.text() === message) {
page.removeListener('console', consoleListener);
resolve();
}
});
})
}
url = `https://storage.googleapis.com/public_website/examples/unity-serverless/build/index.html` +
`?r=${req.query.r || 0}&g=${req.query.g || 0}&b=${req.query.b || 0}`
var scraper = scrapeForConsoleMessage('Screenshotter: capture now');
console.log(`Fetching ${url}`);
page.setViewport({
width: 960,
height: 600
});
page.goto(url);
await scraper;
console.log("Cloud function: Screenshotting")
const gameContainerDOM = await page.$('#gameContainer');
const imageBuffer = await gameContainerDOM.screenshot();
res.set('Content-Type', 'image/png');
res.send(imageBuffer);
};
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Screenshotter : MonoBehaviour {
public TextMesh text;
public void Awake() {
float r = 1, g = 1, b = 1;
// Read r, g and b parameters passed into the query as <URL>?r=0.5?g=0?b=0.1
string [] url_query = Application.absoluteURL.Split(new char[]{'?'});
if (url_query.Length == 2) {
var query = url_query[1];
string [] assignments = query.Split(new char[]{'&'});
foreach(string assignment in assignments) {
string [] pair = assignment.Split(new char[]{'='});
string lhs = WWW.UnEscapeURL(pair[0]);
float rhs = float.Parse(WWW.UnEscapeURL(pair[1]));
if (lhs == "r") r = rhs;
else if (lhs == "g") g = rhs;
else if (lhs == "b") b = rhs;
}
}
// Color the text according to instruction in URL
text.color = new Color(r, g, b, 1);
// Wait for a frame to render
StartCoroutine("snapshot");
}
IEnumerator snapshot() {
yield return new WaitForEndOfFrame();
Debug.Log("Screenshotter: capture now");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment