Skip to content

Instantly share code, notes, and snippets.

@to4iki
Created June 20, 2013 08:00
Show Gist options
  • Save to4iki/5821006 to your computer and use it in GitHub Desktop.
Save to4iki/5821006 to your computer and use it in GitHub Desktop.
canvasアニメーション(円が登っていく動き)
$(function() {
/**
[マウスの座標]
横方向: mx
縦方向: my
反応させるマウス周辺の半径: mr
[アニメーションする円の座標]
横方向: cx
縦方向: cy
アニメーションする円の半径: cr
[衝突判定]
(cx – mx)*(cx – mx)) + ((cy – my)*(cy – my)) <= (cr+mr)*(cr+mr)
**/
// Init Circle
var cnt = -30;
var cy = 330;
var cx = Math.random() * 330;
var cr = Math.random() * 40;
// Init Coordinates of the mouse
var mx = 0;
var my = 0;
var mr = 10;// 反応させるマウス周辺の半径
setInterval(drawCircle, 4);
function drawCircle () {
// Init Canvas
var canvas = document.getElementById('canvas-area');
var ctx = canvas.getContext('2d');
// マウス座標取得
$('#canvas-area').on('mousemove', function(e) {
mx = e.clientX - 100;
my = e.clientY - 100;
});
cy = cnt;
// 衝突判定
if( ((cx - mx)*(cx - mx)) + ((cy - my)*(cy - my)) <= (cr+mr)*(cr+mr) ) {
if (mx > cx) { //マウスが円の左なら右に、右なら左に避ける
cx -= 1.0;
} else if(mx <= cx) {
cx += 1.0;
}
if(my > cy) { //マウスが円の上のほうなら減速、逆なら加速する
cnt += -1.0;
} else {
cnt -= -1.0;
}
}
// Drow Cavas
ctx.globalCompositeOperayion = 'destination-over'; // 合成処理 対象イメージを描画先イメージの裏に表示
ctx.clearRect(0, 0, 300, 300); // canvasを削除
ctx.beginPath(); // 描画サブパスを初期化
ctx.fillStyle = 'rgba(125,125,215,0.5)'; // 形状内に使う色やスタイル
ctx.stroleStyle = 'rgba(125,125,215,0.5)'; // 形状の輪郭に使う色やスタイル
ctx.arc(cx, cy, cr, 0, Math.PI*2, false);
ctx.stroke();
ctx.fill();
cnt --;
// 円が画面いっぱいまで登ったら初期値に戻す
if (cnt < -30) {
cnt = 330;
cx = Math.random() * 330;
cr = Math.random() * 40;
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>circle</title>
<script src="http://code.jquery.com/jquery-2.0.0.min.js"></script>
</head>
<body>
<canvas id="canvas-area" width="300" height="300"></canvas>
<!-- JavaScript Includes -->
<script src="circle.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment