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 Rect(x, y, width, height, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.dx = Math.floor(Math.random() * 10) + 1;
this.dy = Math.floor(Math.random() * 10) + 1;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.width, this.height);
// ctx.fillRect();
}
this.animate = function() {
this.x += this.dx;
this.y += this.dy;
if(this.x + this.width > canvas.width || this.x < 0) {
this.dx = -this.dx;
}
if(this.y + this.height > canvas.height || this.y < 0) {
this.dy = -this.dy;
}
this.draw();
}
}
const box1 = new Rect(10, 10, 50, 50, "red");
const box2 = new Rect(20, 20, 30, 30, "blue");
// box1.draw();
// box2.draw();
move();
function move() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
box1.animate();
box2.animate();
requestAnimationFrame(move);
}
'Javascript > GMA(2302~)' 카테고리의 다른 글
230530 자바스크립트 예제 - 텍스트입력시 몇글자 인지 확인하기(Keydown 이벤트 / .value / .length) (0) | 2023.05.30 |
---|---|
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 |