JavaScriptでCanvasの上に描画した表示を数秒後に消すsetTimeout

5秒で消えちゃうので先に画面をお見せします。

See the Pen
canvas-img-repeat
by pghappy (@pghappy)
on CodePen.

ここから解説。

Canvas上に文字を表示して、5秒後にその文字を消す(ように見せるために再描画する)ということをやります。

まずHTML側でcanvasを用意しておきます。
特にボタンとかは用意せずロードしたタイミングでJavaScriptを動かします。

<body onload="xyz()">
  <canvas id="aaa" width="300" height="300"></canvas>
</body>

ページの読み込み時にxyz()メソッドを起動します。

JavaScriptは以下のようになりました。

var canvas, ctx;
function xyz(){

  canvas = document.getElementById("aaa");
  ctx = canvas.getContext("2d");

  //canvasいっぱいに明るい黄色で塗る
  ctx.fillStyle = 'lightyellow';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  //メッセージを表示する赤色の背景を描画
  var msgBg = {x:canvas.width/2-100, y:canvas.height/2-50, w:200, h:100};
  ctx.fillStyle = "rgb(150,50,50,0.6)";
  ctx.fillRect(msgBg.x, msgBg.y, msgBg.w, msgBg.h);

  //メッセージを設定して表示
  ctx.font = '20px bold sans-serif';
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  ctx.fillStyle = 'white';  
  var msg = {txt:'コココ', x:canvas.width/2, y:canvas.height/2};
  ctx.fillText(msg.txt, msg.x, msg.y);

  //2秒後にrepaintを起動。
  var timerMsg = setTimeout(function() {
      repaint();
      clearTimeout(timerMsg);
  },5000);
  
}

//canvasを黄色で描画するだけ
function repaint() {
  ctx.fillStyle = 'lightyellow';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

ctxとcanvasはグローバル変数で用意。
canvasを明るい黄色でfillRectして塗っています。

その上にメッセージ用の赤色の背景をfillRectし、その上にメッセージをfillTextで表示しています。

その後にsetTimeoutで、無名関数を記述し、5秒後(5000ミリ秒後)に、repaint()メソッドが動くようにしました。

repaint()メソッドはcanvasを黄色で塗るだけです。つまりメッセージもろとも上から塗りつぶしてるイメージですね。メッセージが消えたように見えます。

setTimeoutは無名関数じゃなくて、setTimeout(repaint, 2000)でも動きます。

clearTimeoutは必要なさそうだけど、一応やっておきました。

タイトルとURLをコピーしました