16. ์บ๋ฒ์ค์์ ์ ๋๋ฉ์ด์ ์คํํ๊ธฐ
requestAnimationFrame(์ฝ๋ฐฑ)
์ ๋๋ฉ์ด์ ์ ํ ์์น์์ ๋ค๋ฅธ ์์น๋ก ์ฎ๊ฒจ๊ฐ๋ฉฐ ๊ทธ๋ํฝ ์์๋ฅผ ๊ณ์ ํ๋ฉด์ ๊ทธ๋ ค์ผํ๋ค
์ฆ, ์ขํ๋ฅผ ์ฎ๊ธฐ๊ณ ๊ทธ๋ํฝ ์์๋ฅผ ๊ทธ๋ฆฌ๋ ํจ์๋ฅผ ๋ฐ๋ณตํ๋ค
๋ฌด์์ ์ 20๊ฐ ๋ง๋ค์ด ์์ง์ด๊ธฐ
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.beginPath();
ctx.fillStyle = this.color;
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 < 20; 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 = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
objs.push(new Circle(x, y, radius, color));
}
function update(){
// ์บ๋ฒ์ค ์ง์ฐ๊ธฐ
// objs์ ๊ฐ ์์๋ง๋ค ์ ๋๋ฉ์ด์
์คํํ๊ธฐ <-๋ฐ๋ณต
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();
๋ง๋ฌด๋ฆฌ ์ค์ต2
๋ค๋ชจ ๊ฐ์ฒด 2๊ฐ ๋ง๋ค์ด์ ์์ง์ด๊ธฐ
const canvas=document.querySelector("canvas");
const ctx=canvas.getContext("2d");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
function Rect(x,y,w,h,c){
this.x=x;
this.y=y;
this.w=w;
this.h=h;
this.c=c;
this.dx=Math.floor(Math.random()*10)+1;
this.dy=Math.floor(Math.random()*10)+1;
this.draw=function(){
ctx.beginPath();
ctx.fillStyle=this.c;
ctx.fillRect(this.x,this.y,this.w,this.h,this.c);
}
this.animation=function(){
this.x +=this.dx;
this.y +=this.dy;
if(this.x+this.w>canvas.width || this.x<0){
this.dx = -this.dx;
}
if(this.y+this.h>canvas.height || this.y<0){
this.dy = -this.dy;
}
this.draw();
}
}
const r1 = new Rect(10, 10, 50, 50, "red");
const r2 = new Rect(20, 20, 30, 30, "blue");
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
r1.animation();
r2.animation();
requestAnimationFrame(update);
}
r1.draw();
r2.draw();
update();'๊ณต๋ถ ๊ธฐ๋ก โ๏ธ > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| Do-it! JS ์ค์ต ๋ณต์ต #unit1 (0) | 2023.04.06 |
|---|---|
| JS-Do it! JS - #12์ผ (17,18) (0) | 2023.04.03 |
| JS-Do it! JS - #10์ผ (14,15) (0) | 2023.04.01 |
| JS-Do it! JS - #9์ผ (11,12,13) (0) | 2023.03.30 |
| JS-Do it! JS - #8์ผ (09,10) (0) | 2023.03.23 |