Web에 그림 그리기 <canvas>"2d"</canvas> #2 - Rectangle 그리기

Fstone·2020년 12월 9일
0

canvas

목록 보기
2/2
post-thumbnail

App.js

import Rectangle from "./components/basic/Rectangle.js";

export default class App {
  constructor() {
    this.canvas = document.createElement("canvas");
    document.body.appendChild(this.canvas);
    this.ctx = this.canvas.getContext("2d");

    this.draw.bind(this);
    this.draw();
  }

  draw() {
    this.stageWidth = document.body.clientWidth;
    this.stageHeight = document.body.clientHeight;

    this.canvas.width = this.stageWidth;
    this.canvas.height = this.stageHeight;

    console.log(this.canvas.width, this.canvas.height);

    this.x = this.stageWidth / 5;
    this.y = this.stageHeight / 5;

    this.width = this.stageWidth / 5;
    this.height = this.stageHeight / 5;

    console.log(this.x, this.y, this.width, this.height);

    this.rectangle = new Rectangle(this.x, this.y, this.width, this.height);
    this.rectangle.draw(this.ctx);
  }
}

  • canvas.width or height : canvas 요소의 크기 값을 설정해 주어야 Web에서 확인할 수 있다.

  • x, y, width, height : 임의의 값을 설정해도 됐지만 조금씩 연습하기 위해 clientWidth, clientHeight 값을 이용해 좌표 축과 사각형의 크기를 정해주었다.

Rectagle.js

export default class Rectangle {
  constructor(x, y, width, height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }

  draw(ctx) {
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}
  • ctx.fillRect(x, y, width, height) : Rect는 아마 Rectangle의 약자. arguments로 받은 x, y 위치에서 width, height 크기의 색이 채워진 사각형을 그린다.

Reference

https://developer.mozilla.org/ko/docs/Web/HTML/Canvas/Tutorial/Drawing_shapes

https://www.youtube.com/channel/UCdeWxKJuvtUG2xyN6pOJEvA

0개의 댓글