Last active
October 21, 2021 04:58
-
-
Save watab0shi/f920b55d3f0ae1f045f967574cab6b4a to your computer and use it in GitHub Desktop.
three.js で render ループ中に canvas 要素の dataURL を取得する
This file contains hidden or 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
| /** | |
| * three.js canvas | |
| */ | |
| class GLCanvas { | |
| /** | |
| * @param {Object} param | |
| * @param {HTMLCanvasElement} param.element | |
| */ | |
| constructor({ element }) { | |
| this._element = element; | |
| // create _renderer, _scene, _camera | |
| } | |
| /** | |
| * Base64 | |
| * @type {string} | |
| */ | |
| get dataURL() { | |
| return this._element.toDataURL(); | |
| } | |
| /** | |
| * 次フレームのレンダリング後にdataURLを返す | |
| * @returns {Promise<string>} | |
| */ | |
| getDataURL() { | |
| return new Promise((resolve) => { | |
| this._getDataURL = () => { | |
| resolve(this.dataURL); | |
| }; | |
| }); | |
| } | |
| render() { | |
| this._renderer.render(this._scene, this._camera); | |
| if (this._getDataURL) {// レンダリング後にdataURL取得 | |
| this._getDataURL(); | |
| this._getDataURL = null; | |
| } | |
| } | |
| } |
This file contains hidden or 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
| /** | |
| * ページ | |
| */ | |
| class Page { | |
| constructor() { | |
| // ... | |
| this._canvas = new GLCanvas(); | |
| this._onAnimationFrame(); | |
| window.addEventListener('click', () => { this._onClick(); }); | |
| } | |
| _onAnimationFrame() { | |
| this._canvas.render(); | |
| window.requestAnimationFrame(() => { this._onAnimationFrame(); }); | |
| } | |
| async _onClick() { | |
| // console.log(this._canvas.dataURL);// ← レンダリング前なので空白のcanvasになっちゃう | |
| const dataURL = await this._canvas.getDataURL();// ← Promise を返してるので await で取得できる | |
| console.log(dataURL); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment