三角関数で円運動|HTML5

三角関数で円運動|HTML5

三角関数で円運動|HTML5(HTML5, JavaScript, CSS3) : デモ

三角関数で円運動|HTML5(HTML5, JavaScript, CSS3) : ZIPファイル(2kb)

1.HTML

<!DOCTYPE html>
<html lang="jp">
    <head>
        <meta charset="UTF-8" />
        <title>三角関数と円|Trigonometric function and circle</title>
        <link href="css/base.css" rel="stylesheet" type="text/css">
        <script src="js/base.js"></script>
    </head>
    <body>
        <div id="contents">
            <canvas id="canvas" width="100" height="100">
            </canvas>
        </div>
    </body>
</html>

2.CSS

@charset "utf-8";
  
body
{
    margin:0;
    padding:0;
    background-color: #fff;
    font-family:Helvetica, HiraKakuProN-W3, sans-serif; 
    font-size:25px;
    color:#fff;
}
  
#contents
{
    position: absolute;
    top: 0;
    left: 0;
    width: 300px;
    height:300px;
    border: 1px solid #000;
    overflow:hidden;
}
  
#canvas
{
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height:100px;
}

3.JavaScript

base.js

window.addEventListener(“load”, init, false);

function init()
{
var theCanvas = document.getElementById(“contents”);
var offsetX = (theCanvas.currentStyle || document.defaultView.getComputedStyle(theCanvas,”)).width;
offsetX = Number(offsetX.replace(‘px’,”));
offsetX = offsetX / 2;
var offsetY = (theCanvas.currentStyle || document.defaultView.getComputedStyle(theCanvas,”)).height;
offsetY = Number(offsetY.replace(‘px’,”));
offsetY = offsetY / 2;

theCanvas = document.getElementById(“canvas”);
var ctx = theCanvas.getContext(“2d”);

var radian = 0;
var radius = 100;
var speed = 0.05;
var n = 10;

setDraw();

function animation()
{
theCanvas.style.left = (offsetX-n+Math.sin(radian)*radius)+’px’;
theCanvas.style.top = (offsetY-n+Math.cos(radian)*radius)+’px’;
radian+=speed;
}
setInterval(animation,1000/60);

function setDraw()
{
ctx.fillStyle=”#000000″;
ctx.beginPath();
//context . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] )
//x,y: center
ctx.arc(n,n,n,0,Math.PI*2,true);
ctx.fill();
theCanvas.style.top=(offsetY-n)+’px’;
theCanvas.style.left=(offsetX-n)+’px’;
}
}

コメントを残す

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