Skip to content

Instantly share code, notes, and snippets.

@watab0shi
Last active October 21, 2021 04:58
Show Gist options
  • Select an option

  • Save watab0shi/f920b55d3f0ae1f045f967574cab6b4a to your computer and use it in GitHub Desktop.

Select an option

Save watab0shi/f920b55d3f0ae1f045f967574cab6b4a to your computer and use it in GitHub Desktop.
three.js で render ループ中に canvas 要素の dataURL を取得する
/**
* 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;
}
}
}
/**
* ページ
*/
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