Last active
May 29, 2016 04:23
-
-
Save nishinoshake/de1a6a42a4317547378f to your computer and use it in GitHub Desktop.
Canvasで跳ね返るボール
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function(){ | |
$('<canvas id="yes"></canvas>').appendTo('body'); | |
var canvas = document.getElementById('yes'), | |
ctx = canvas.getContext('2d'), | |
ww = $(window).width(), | |
wh = $(window).height(), | |
circle = [], | |
color = [ | |
'#303F9F', | |
'#3F51B5', | |
'#C5CAE9', | |
'#727272', | |
'#4CAF50', | |
'#FFC107' | |
]; | |
function Circle(ctx) { | |
this.ctx = ctx; | |
this.speed = { | |
x: 30 * Math.random() - 15, | |
y: 30 * Math.random() - 15 | |
}; | |
this.position = { | |
x: ww * Math.random(), | |
y: wh * Math.random() | |
}; | |
this.color = color[~~(Math.random() * color.length)]; | |
this.radius = 50 * Math.random(); | |
} | |
Circle.prototype.draw = function() { | |
ctx.beginPath(); | |
ctx.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2); | |
ctx.fillStyle = this.color; | |
ctx.fill(); | |
}; | |
Circle.prototype.rebound = function() { | |
if ( this.position.x >= ww - this.radius || | |
this.position.x <= this.radius | |
) { | |
this.speed.x *= -1; | |
} | |
if ( | |
this.position.y >= wh - this.radius || | |
this.position.y < this.radius | |
) { | |
this.speed.y *= -1; | |
} | |
}; | |
var resizeCanvas = function() { | |
$(window).on('resize', function() { | |
$(canvas).attr('width', ww); | |
$(canvas).attr('height', wh); | |
$(canvas).width(ww); | |
$(canvas).height(wh); | |
}).trigger('resize'); | |
}; | |
var render = function() { | |
var _this = this; | |
(function render(){ | |
requestAnimationFrame(render); | |
ctx.clearRect(0, 0, ww, wh); | |
for ( var i = 0, length = circle.length; i < length; i++ ) { | |
circle[i].rebound(); | |
circle[i].position.x += circle[i].speed.x; | |
circle[i].position.y += circle[i].speed.y; | |
circle[i].draw(); | |
} | |
})(); | |
}; | |
for ( var i = 0; i < 20; i++ ) { | |
circle[i] = new Circle(); | |
} | |
resizeCanvas(); | |
render(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment