HTML
<body>
<canvas></canvas>
</body>
Javascript
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function Circle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.dx = Math.floor(Math.random() * 4) + 1;
this.dy = Math.floor(Math.random() * 4) + 1;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fill();
}
this.animate = function() {
this.x += this.dx;
this.y += this.dy;
if(this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if(this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy;
}
this.draw();
}
}
const objs = [];
for(let i = 0; i < 30; i++) {
const radius = Math.floor((Math.random() * 50) + 10);
const x = Math.random() * (canvas.width - radius * 2) + radius;
const y = Math.random() * (canvas.height - radius * 2) + radius;
const color = `rgba(${Math.random()* 255}, ${Math.random()* 255}, ${Math.random()* 255}, ${Math.random() * 1})`;
objs.push(new Circle(x, y, radius, color));
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(let i = 0; i < objs.length; i++) {
let obj = objs[i];
obj.animate();
}
requestAnimationFrame(update); //재귀함수
}
update();
'Javascript > GMA(2302~)' 카테고리의 다른 글
230530 자바스크립트 예제 - 버튼클릭시 색상변경 (*setProperty / Math.random / hsl) (0) | 2023.05.30 |
---|---|
230502 자바스크립트 캔버스 웹브라우저 안에서 움직이는 도형 만들기 (0) | 2023.05.18 |
230428 자바스크립트 fetch( ) 사용하여 Json 명언 파일 불러와 새로고침시 명언 바뀌어 출력하기 (0) | 2023.05.18 |
230428 자바스크립트 async( ) / fetch( ) 활용하여 Json 파일 출력하기 (0) | 2023.05.18 |
23.04.27 자바스크립트 JSON데이터를 프로미스 객체로 반환하는 fetch( ), async함수 (0) | 2023.04.27 |