LoginSignup
1
4

More than 5 years have passed since last update.

canvasのパフォーマンス向上

Posted at

プリレンダリング

imgタグではなく、canvasタグを配列に格納

preloadCanvas.js
export function preloadCanvas (paths) {
  return new Promise((resolve, reject) => {
    let canvasAry = [];
    let loadCount = 0;
    paths.forEach((path, index) => {
      // loadの中に入れるとcanvasの順番が変わってしまう
      // 場合があるので、外に出しておく
      const canvas = document.createElement("canvas");
      canvasAry.push(canvas);

      let img = new Image();
      img.src = path;
      img.addEventListener('load', () => {
        // 1度canvasに描く
        const ctx = canvas.getContext("2d");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);

        loadCount += 1;
        if (loadCount == paths.length) {
          resolve(canvasAry)
        }
      }, false)
    })
  })
}
script.js
import {preloadCanvas} from "./lib/preloadCanvas";
// 画像のパスを渡して、一度描画したcanvasを得る
const preloadedCanvasAry = preloadCanvas(fileAry);

・・・(Promise処理とか

// 一度描画したcanvasを再びcanvasに描画する
ctx.drawImage(preloadedCanvasAry[index], 0, 0, canvas.width, canvas.height)


参考
HTML5 canvas のパフォーマンスの改善

1
4
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
1
4