s 6——クラス運用-煌びやかで美しいボール-対象バージョンに向かう
20559 ワード
css
body {
margin: 150px;
}
#father{
position: relative;
}
#canvas {
box-shadow: 0 0 10px;
position: absolute;
top: 0;
left: 0;
}
#btn{
margin: 10px;
width: 100px;
height: 50px;
position: absolute;
top: 0;
right: 0;
}
html<div id="father">
<canvas id="canvas"> canvas>
<button id="btn">surprisebutton>
div>
js(アンダースコアの導入が必要です.) <script src="../../frame/underscore/underscore.js"></script>
<script>
window.onload = function () {
//1.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 1000;
canvas.height = 600;
canvas.style.backgroundColor = 'black';
//2.
class Ball {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.r = 40;
}
/**
*
*/
render() {
ctx.save();
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
//3.
class MoveBall extends Ball {
constructor(x, y, color) {
super(x, y, color);
//
this.dX = _.random(-5, 5);
this.dY = _.random(-5, 5);
this.dR = _.random(1, 3);
}
upDate() {
this.x += this.dX;
this.y += this.dY;
this.r -= this.dR;
if (this.r < 0) {
this.r = 0;
}
}
}
//4.
let ballArr = [];
let colorArr = ['red', 'green', 'blue', 'skyblue', 'yellow', 'pink', 'orange'];
//5.
canvas.addEventListener('mousemove', function (e) {
ballArr.push(new MoveBall(e.offsetX,e.offsetY,colorArr[_.random(0,colorArr.length-1)]));
console.log(ballArr);
});
//6.
//
let check=true;
let btn=document.getElementById('btn');
btn.onclick=function(){
check=!check;
};
setInterval(function(){
//
if(check){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
//
for(let i=0;i<ballArr.length;i++){
ballArr[i].render();
ballArr[i].upDate();
}
},50)
}
</script>