canvas サンプル

【HTML5を知ろう】 Canvasでアニメーション!②

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8lang="ja" prefix="og: http://ogp.me/ns#"">
<title>Sample</title>
</head>
<body>

<div>
    <canvas width="300" height="300" id="sumple" style="background-color:rgba(0, 0, 0, 1);"></canvas>
</div>

<script>
function test() {
    var canvas = document.getElementById('sumple');
    var circle = canvas.getContext('2d');
    var circle_w = canvas.width;
    var circle_h = canvas.height;
    var x = 150;
    var y = 20;
    var z = 20;
    
    (function circle_animation() {
        circle.clearRect(0, 0, circle_w, circle_h);
        circle.beginPath();
        circle.arc(x, y, z, 0, 2*Math.PI, false);
        circle.fillStyle = 'white';
        circle.fill();
        
        if (y >= (canvas.height-z)) {
            y = 20;
        }
        y += 2;
        
        requestAnimationFrame(circle_animation);
    })();
}

test();

</script>