✅ 버튼만들기
2. 버튼 크기조절하기
draw(ctx):function {
var d = this.radius;
var hw = Math.sqrt((d * d) - ((d / 2) * (d / 2)));
var pos1 = { x: this.bx, y: this.by - d };
var pos2 = { x: this.bx - hw, y: this.by + (d / 2) }
var pos3 = { x: this.bx + hw, y: this.by + (d / 2) }
this.shapePath = new Path2D();
this.shapePath.moveTo(pos1.x, pos1.y);
this.shapePath.lineTo(pos2.x, pos2.y);
this.shapePath.lineTo(pos3.x, pos3.y);
}
👉 draw할때 각 지점의 값을 정하고 그리는 구조 ▶ radius의 설정값이 변하면 새로운 원을 그려야 하는데 radius를 전역변수로 세팅하면 해결될까? ▶ 세팅값을 전역변수가 있는 위(생성자 안)로 올려봄
function Button(x, y) { // 클래스 겸 생성자로 만들어줌
this.bx = x || 800;
this.by = y || 100;
this.radius = 30; // 여기 값이 변해도 function Button자체가 생성자이기 때문에 의미없음
// var d = this.radius;
// var hw = Math.sqrt((d * d) - ((d / 2) * (d / 2)));
// var pos1 = { x: this.bx, y: this.by - d };
// var pos2 = { x: this.bx - hw, y: this.by + (d / 2) }
// var pos3 = { x: this.bx + hw, y: this.by + (d / 2) }
// this.shapePath = new Path2D();
// this.shapePath.moveTo(pos1.x, pos1.y);
// this.shapePath.lineTo(pos2.x, pos2.y);
// this.shapePath.lineTo(pos3.x, pos3.y);
this.invalid(); // 값 초기화용 함수 만들기 > 각 지점의 값들을 다시 세팅해준다
}
👉 전역변수가 있는 생성자 내부는 처음 도형이 만들어질때만 적용되어 작동되므로 변경값이 draw로 전달되진 않는다. (*생성자로써 함수 안에 들어가있기 때문에 자바에서 쓰던 메인클래스의 전역변수와는 느낌이 다름) ▶ 따라서 전체 값을 재설정 할 수 있는 invalid()를 프로토타입으로 같이 만들어준다.
invalid: function () {
var d = this.radius;
var hw = Math.sqrt((d * d) - ((d / 2) * (d / 2)));
var pos1 = { x: this.bx, y: this.by - d };
var pos2 = { x: this.bx - hw, y: this.by + (d / 2) }
var pos3 = { x: this.bx + hw, y: this.by + (d / 2) }
this.shapePath = new Path2D();
this.shapePath.moveTo(pos1.x, pos1.y);
this.shapePath.lineTo(pos2.x, pos2.y);
this.shapePath.lineTo(pos3.x, pos3.y);
}
👉 각 지점을 구하는 값들이 invalid함수 안으로 넘어오게 되고, 이 값을 기준으로 draw가 진행됨.
//button.js===============================
function Button(x, y) { // 클래스 겸 생성자로 만들어줌
this.bx = x || 800;
this.by = y || 100;
this.radius = 30; //여기있는 값은 생성자로 선언할때만 처리되므로 아래에서 값을 바꾼다고 해서 변경되지않음 > invalid함수를 만들어주게됨
this.invalid(); // 값 초기화 (*여기서는 그리기위한 값 세팅을 위해 invalid 사용)
}
Button.prototype = {
constructor: Button
, update: function () {
if (this.radius < 40) {
this.radius++;
}
// this.radius = ++this.radius % 40; //나머지연산자를 사용해서 업데이트값이 40을 넘지않도록함
// this.radius++;
this.invalid();
}
, draw: function (ctx) {
var originFillstyle = ctx.fillStyle;
ctx.fillStyle = "orange";
ctx.fill(this.shapePath);
ctx.fillStyle = originFillstyle;
}
, isLocated: function (x, y) {
var isIn = ctx.isPointInPath(this.shapePath, x, y) //해당 도형 내 좌표가 들어가있는지 확인하는 함수
console.log(isIn);
return isIn;
}
, invalid: function () {
var d = this.radius;
var hw = Math.sqrt((d * d) - ((d / 2) * (d / 2)));
var pos1 = { x: this.bx, y: this.by - d };
var pos2 = { x: this.bx - hw, y: this.by + (d / 2) }
var pos3 = { x: this.bx + hw, y: this.by + (d / 2) }
this.shapePath = new Path2D();
this.shapePath.moveTo(pos1.x, pos1.y);
this.shapePath.lineTo(pos2.x, pos2.y);
this.shapePath.lineTo(pos3.x, pos3.y);
}
, action: function () {
this.radius = 40; // 값변경
this.invalid(); // (*여기서는 변경된 값 세팅을 위해 invalid 사용)
}
}
//game1.js========================
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
curBall.setActive(); //처음 선택된 버튼
var upButton = new Button(800, 100);
canvas.onclick = function (e) {
//위에있는게 우선순위를 가진다
if (upButton.isLocated(e.x, e.y)) {
console.log("삼각형 선택됨")
upButton.action(); // 크기 변경됨
return;
}
for (var ball of balls) {
if (ball.isLocated(e.x, e.y)) {
curBall.setActive(false);
curBall = ball;
console.log("선택")
curBall.setActive();
return;
}
}
curBall.moveTo(e.x, e.y);
console.log("외부선택")
}
window.setInterval(function () {
upButton.update(); // 크기가 지속적으로 변경됨
// ball관련 interval내용 생략
}, 17); // 1000/50 > 20fps 초당 20프레임
✅ 자바스크립트 ES6
#️⃣ CanvasRenderingContext2D: isPointInPath() 메서드
CanvasRenderingContext2D: isPointInPath() method - Web APIs | MDN
The CanvasRenderingContext2D.isPointInPath() method of the Canvas 2D API reports whether or not the specified point is contained in the current path.
developer.mozilla.org
✅ ES6에서 추가된 내용들
https://262.ecma-international.org/13.0/#sec-ecmascript-language-source-code
ECMAScript® 2022 Language Specification
The first and subsequent editions of ECMAScript have provided, for certain operators, implicit numeric conversions that could lose precision or truncate. These legacy implicit conversions are maintained for backward compatibility, but not provided for BigI
262.ecma-international.org
🟩 값, 변수, 컬렉션
#️⃣ let키워드
변수를 선언하지 않아도 변수를 쓸수있는 문제 혹은 var를 선언해도 지역변수가 아닌 문제 (window객체가 되어서 사용됨)
▶ let으로 선언하게 됨
#️⃣ 변수 중복선언이 불가하게 됨
{
let x = 30;
let y = 50;
}
console.log(x, y); // 괄호 밖에 있으므로 출력불가
//---------------------
for (let i = 0; i < 5; i++); //var로 선언했으면 for문이 끝나도 값이 공유되어 출력되지만 let으로 하면 출력불가
console.log(i); //출력안됨
//---------------------
let direction = 1;
const North = 1; // 상수형변수
North++; //let으로 선언했다면 값이 변경되지만 const는 상수형변수로 에러가 뜬다.
console.log("direction" + direction);
console.log("North" + North);
'😵 ~23.11.10' 카테고리의 다른 글
0731 | JS ES6 :: 함수 (나머지값 받기, spread operator, default value, arrow function과 this가 가리키는 객체 / bind, call, apply ) (0) | 2023.07.31 |
---|---|
0728 | JS ES6 :: 템플릿문자열${}, String.raw / 향상된 JSON 상태표현식 / 객체와 배열 구조분해할당 (0) | 2023.07.30 |
0726 | 움직임에 대한 충돌 조건식 / 삼각형 그리기 (2) | 2023.07.27 |
0725 | JS 볼 객체와 생성자, 프로토타입 만들기 / 선택한 좌표로 볼 이동시키기 (0) | 2023.07.27 |
0724 | JS 상태 값 저장하기, 애니메이션 이동 , 구조화 (3) | 2023.07.24 |