Mosaic Size

by hyeyoon

HTML

<canvas id="canvas"></canvas>
<canvas id="smallCanvas"></canvas>
<canvas id="expandCanvas"></canvas>

JavaScript

function draw() {
	const canvas = document.querySelector('#canvas');
	const ctx = canvas.getContext('2d');
  const img = new Image();
  img.onload = function() {
	  canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
    
    drawSmallImage();
    drawExpandImage();
  };
  img.src = 'https://picsum.photos/400';
}

function drawSmallImage() {
	const amount = 50;
	const baseCanvas = document.querySelector('#canvas');
  const { width, height } = baseCanvas;
  // 모자이크 효과를 추가할 캔버스 생성
  const newCanvas = document.querySelector('#smallCanvas');
  newCanvas.width = width;
  newCanvas.height = height;
 	const ctx = newCanvas.getContext('2d');
  
  // 모자이크 효과의 직각 느낌이 날 수 있게 부드럽게 이미지를 처리하는 것을 비활성화
	ctx.imageSmoothingEnabled = ctx.webkitImageSmoothingEnabled = ctx.msImageSmoothingEnabled = ctx.mozImageSmoothingEnabled = false;  
  // 이미지를 축소할 비율
  const ratio = 1 - amount / 100;
  const pW = width * (ratio > 0 ? ratio : 0.01);
  const pH = height * (ratio > 0 ? ratio : 0.01);

  // 캔버스에 이미지를 축소한 비율만큼 축소해서 그린다
  ctx.drawImage(baseCanvas, 0, 0, pW, pH);
}

function drawExpandImage() {
	const amount = 85;
	const baseCanvas = document.querySelector('#canvas');
  const { width, height } = baseCanvas;
  // 모자이크 효과를 추가할 캔버스 생성
  const newCanvas = document.querySelector('#expandCanvas');
  newCanvas.width = width;
  newCanvas.height = height;
 	const ctx = newCanvas.getContext('2d');
  
  // 모자이크 효과의 직각 느낌이 날 수 있게 부드럽게 이미지를 처리하는 것을 비활성화
	ctx.imageSmoothingEnabled = ctx.webkitImageSmoothingEnabled = ctx.msImageSmoothingEnabled = ctx.mozImageSmoothingEnabled = false;  
  // 이미지를 축소할 비율
  const ratio = 1 - amount / 100;
  const pW = width * (ratio > 0 ? ratio : 0.01);
  const pH = height * (ratio > 0 ? ratio : 0.01);

  // 캔버스에 이미지를 축소한 비율만큼 축소해서 그린다
  ctx.drawImage(baseCanvas, 0, 0, pW, pH);
  // 위에서 그린 축소한 이미지를 원래 크기에 맞게 늘려서 그린다
  ctx.drawImage(newCanvas, 0, 0, pW, pH, 0, 0, width, height);
}

draw();