LoginSignup
0
0

More than 5 years have passed since last update.

【PlayCanvas】画面をキャプチャして表示/ダウンロードする

Last updated at Posted at 2017-12-13

この記事は PlayCanvas Advent Calendar 2017 の11日目の記事です。

やり方

HTML5 canvasのtoDataURL()を利用します。
公式サンプルがあるのでまずはそちらから
Capturing a screenshot

良く躓く落とし穴

設定

Setting > RENDERING > Preserve Drawing Bufferのチェックを必ず入れる必要があります(デフォルトではfalse)
これを入れないとapplication-canvasのtoDataURL()にキャンバスデータが乗りません
image.png

window.openだと開かない

この前まで動いてたんですが、突然動かなくなりました
Take ScreenShotボタンを押してもabout:blankのまま次に進みません。
choromeでスクリーンショットが撮れません | PlayCanvasコミュニティ

動くブラウザと動かないブラウザがあるようなので、おそらくブラウザの問題かなーと思います。
htmlにimgを用意してsrcで流したらうまく動いたのでキャプチャはうまくいっているようです。

画像をダウンロードする

直接ローカルにダウンロードするような実装も可能です。
screenshot.jsを以下のように書き換えます

screenshot.js
// NOTE: THIS SCRIPT ONLY WORKS IF 'PRESERVE DRAWING BUFFER' IS ENABLED IN PROJECT SETTINGS

var Screenshot = pc.createScript('screenshot');

Screenshot.prototype.initialize = function() {
    this.app.on('ui:takeScreenshot', function () {
        this.takeScreenshot();
    }, this);

};

Screenshot.prototype.takeScreenshot = function () {
    // Get application canvas element
    var canvas = document.getElementById ('application-canvas');

    // Get image data from canvas
    var imageData = canvas.toDataURL ();

    var downloadElement = document.createElement("a");
    downloadElement.href = imageData;
    downloadElement.download = "image.png";
    downloadElement.click();

    // Show the image data in a new window/tab. 
    //window.open (imageData);
};

エレメントのdownload属性は使えるブラウザと使えないブラウザがあるので注意してください
https://caniuse.com/#search=download

発展形はこちら

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0