Mosaic Effect
imageSmoothingEnabled
by hyeyoon
HTML
<canvas id="canvas"></canvas>
<canvas id="smoothMosaicCanvas"></canvas>
<canvas id="mosaicCanvas"></canvas>
CSS
canvas {
margin: 5px;
}
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);
drawSmoothMosaic();
drawMosaic();
};
img.src = 'https://picsum.photos/400';
}
function drawSmoothMosaic() {
const amount = 85;
const baseCanvas = document.querySelector('#canvas');
const { width, height } = baseCanvas;
// 모자이크 효과를 추가할 캔버스 생성
const newCanvas = document.querySelector('#smoothMosaicCanvas');
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);
}
function drawMosaic() {
const amount = 85;
const baseCanvas = document.querySelector('#canvas');
const { width, height } = baseCanvas;
// 모자이크 효과를 추가할 캔버스 생성
const newCanvas = document.querySelector('#mosaicCanvas');
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);
// 위에서 그린 축소한 이미지를 원래 크기에 맞게 늘려서 그린다
...