문제가 있을 시 알려주시면 감사하겠습니다.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<script src="./js/app.js" type="module"></script>
</body>
</html>
css
html, body {width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;}
canvas {background: #00c3ff; width: 100%; height: 100%;}
javascript
app.js (module)
import { Bubble } from './bubble.js';
class App {
constructor () {
// init canvas
this.canvas = document.createElement('canvas');
document.body.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
this.pixelRatio = window.devicePixelRatio > 1 ? 2 : 1;
// resize
window.addEventListener('resize', this.resize.bind(this), false);
this.resize();
// variable
this.mousedownX = 0;
this.mousedownY = 0;
this.mouseupX = 0;
this.mouseupY = 0;
// object
this.bubble = new Bubble(this.stageWidth, this.stageHeight);
// mouse event
this.canvas.addEventListener('mousedown', this.mouseDown.bind(this));
this.canvas.addEventListener('mouseup', this.mouseUp.bind(this));
// animation
window.requestAnimationFrame(this.animate.bind(this));
}
resize () {
this.stageWidth = document.body.clientWidth;
this.stageHeight = document.body.clientHeight;
this.canvas.width = this.stageWidth * this.pixelRatio;
this.canvas.height = this.stageHeight * this.pixelRatio;
this.ctx.scale(this.pixelRatio, this.pixelRatio);
}
animate () {
window.requestAnimationFrame(this.animate.bind(this));
this.ctx.clearRect(0, 0, this.stageWidth, this.stageHeight)
this.bubble.draw(this.ctx);
}
mouseDown (e) {
this.mousedownX = e.offsetX;
this.mousedownY = e.offsetY;
}
mouseUp (e) {
this.mouseupX = e.offsetX;
this.mouseupY = e.offsetY;
let distanceX = this.mousedownX - this.mouseupX;
let distanceY = this.mousedownY - this.mouseupY;
if(distanceX === 0 && distanceY === 0) {
this.bubble.move(this.mouseupX, this.mouseupY);
}
}
}
window.onload = () => {
new App();
}
bubble.js (module)
export class Bubble {
constructor (width, height) {
this.width = width;
this.height = height;
this.click_x = this.width / 2;
this.click_y = this.height / 2;
this.x = 0;
this.y = 0;
this.speed = 20;
}
draw (ctx) {
this.x = this.x + ((this.click_x - this.x) * (1 / this.speed));
this.y = this.y + ((this.click_y - this.y) * (1 / this.speed));
ctx.beginPath();
ctx.arc(this.x, this.y, 100, 0, Math.PI * 2, true);
ctx.strokeStyle = '#ffffff';
ctx.fillStyle = '#ffffff';
ctx.lineWidth = 3;
ctx.stroke();
ctx.fill();
ctx.closePath();
}
move (click_x, click_y) {
this.click_x = click_x;
this.click_y = click_y;
}
}
결과
마우스 클릭시 하얀 공이 해당 좌표로 이동함.
'canvas' 카테고리의 다른 글
canvas 마우스 클릭으로 선 그리기 (0) | 2021.07.01 |
---|---|
canvas 마우스를 따라다니는 원 (0) | 2021.06.23 |