3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

canvas でダブルバッファリング的なことをする

Posted at

やること

タイトルのままです。最近はブラウザの描画速度もかなり高速で、あんまり気にすることもないのですが、たまに必要になるので覚書です。

コード

double_buffer.js
function draw()
{
    var c1, ctx1;
    var c2, ctx2;
    var dat;

    c1 = document.getElementById("canvas1");
    ctx1 = c1.getContext("2d");
    if ( ctx1 == null ) return;

    c2 = document.getElementById("canvas2");
    ctx2 = c2.getContext("2d");
    if ( ctx2 == null ) return;

    ctx1.fillStyle = "gray";
    ctx1.fillRect( 0, 0, 300, 200 );

    dat = ctx1.getImageData(0,0, 300, 200);
    ctx2.putImageData(dat, 0,0 );
}

draw();
double_buffer.html
<!DOCTYPE html>
<html>
<body>
    <canvas id="canvas1" width="300" height="200" hidden></canvas>
    <canvas id="canvas2" width="300" height="200"></canvas>
    <script src="double_buffer.js"></script>
</body>
</html>

hidden な canvas1 を gray に塗り潰して、それを canvas2 にコピーしているだけです。灰色の canvas が表示されたら成功です。失敗していれば、白色の(gray でない)canvasが表示されます。

ポイント

hidden な canvas は clientWidth と clientHeight は 0 になるようです(ブラウザによるのかも)。なので、コピーする範囲は固定値にするとか、canvas タグ内から読むとか何か工夫が必要です(多分)。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?