JavaScriptの練習(Loop)

MDNのサンプルがなんとなく気に入ってしまい、自分でも作ってみました
<canvas>の使い方を調べるのに時間がかかりましたが、なんとなく使い方もわかったし、自分で興味を持って取り組みことは大事ですね。色を変えたりして・・・。

本当は、ゆっくりバブルができるようにしたかったのですが、JavaScriptにはsleepやwaitがないとのこと。うまくできませんでしたが、失敗例を残しておきます。
index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bubble</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Bubble</h1>
    <button class="setBubble">Set</button><br>
    <canvas id="canvas" width="500" height="300">
    </canvas>
  </body>
  <script src="script.js"></script>
</html>

script.js

/*
This is a JavaScript (JS) file.
JavaScript is the programming language that powers the web.

To use this file, place the following <script> tag just before the closing </body> tag in your HTML file, making sure that the filename after "src" matches the name of your file...

    <script src="script.js"></script>

Learn more about JavaScript at https://developer.mozilla.org/en-US/Learn/JavaScript

When you're done, you can delete all of this grey text, it's just a comment.
*/
var cmdSetBubble = document.querySelector('.setBubble');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

function setBubble(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < 100; i++) {
    window.setTimeout("drawBubble()",100);
  }
}

function drawBubble() {
  ctx.beginPath();
  ctx.fillStyle = 'rgba(255,128,64,0.5)';
  ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, Math.random() * Math.min(canvas.height,  canvas.width) / 6, 0, 2 * Math.PI);
  ctx.fill();
}

cmdSetBubble.addEventListener('click', setBubble);

類似投稿

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.