HTML canvas scaling image without library

modric·2024년 4월 24일

fabric.js를 사용하였을 때는 scaleX, scaleY가 있어서 큰 이미지와 캔버스의 가로세로 상대 비율만 계산하면 이미지를 캔버스 크기에 맞게 로드하는 것을 빨리 구현할 수 있었다.
그러나 라이브러리를 사용하지 않고 구현하려니 다소 어렵다.
이 코드는 centerShift_x, centerShift_y가 있어서 프레임 세로 가로 항상 가운데에 로드되는 점이 좋다.

 /**
   * Draws a scaled image on the canvas.
   * @method drawImageScaled
   * @param {CanvasRenderingContext2D} ctx The rendering context of the canvas.
   * @param {HTMLImageElement} img The image to be drawn.
   */
  function drawImageScaled(
    ctx: CanvasRenderingContext2D,
    img: HTMLImageElement,
  ) {
    var canvas = ctx.canvas;
    var hRatio = canvas.width / img.width;
    var vRatio = canvas.height / img.height;
    var ratio = Math.min(hRatio, vRatio);
    var centerShift_x = (canvas.width - img.width * ratio) / 2;
    var centerShift_y = (canvas.height - img.height * ratio) / 2;

    ctx.drawImage(
      img,
      0,
      0,
      img.width,
      img.height,
      centerShift_x,
      centerShift_y,
      img.width * ratio,
      img.height * ratio,
    );
  }

https://stackoverflow.com/questions/23104582/scaling-an-image-to-fit-on-canvas

profile
안녕하세요 카페에서 코딩하면 안 일어나기 라는 일을 잘합니다

0개의 댓글