JSFiddle - React, Tailwind, and code Playground
by Bartosz Zieliński
HTML
<canvas width="600" height="600" id="c"></canvas>
JavaScript
var canvas = $('#c')[0];
var img = $('<img>');
img[0].src = "https://dl.dropboxusercontent.com/u/1268089/newspaces-1000-x-1000-.png";
img.load(function(){
console.log("loaded");
var sourceWidth = 1000;
var sourceHeight = 1000;
var targetWidth = 120;
var targetHeight = 120;
var steps = Math.ceil(Math.log(sourceWidth / targetWidth) / Math.log(2));
var oc = document.createElement('canvas'),
octx = oc.getContext('2d');
oc.width = sourceWidth;
oc.height = sourceHeight;
var bc = document.createElement('canvas'),
bctx = bc.getContext('2d');
bc.width = sourceWidth;
bc.height = sourceHeight;
var ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled=true;
for(var i = 0; i < steps-1; i++ ){
sourceWidth >>= 1;
sourceHeight >>= 1;
if (i == 0){
octx.drawImage(img[0],0,0,sourceWidth,sourceHeight);
}else if( i%2 == 0){
octx.clearRect(0,0,sourceWidth,sourceHeight);
octx.drawImage(bc,0,0,sourceWidth<<1,sourceHeight<<1,0,0,sourceWidth,sourceHeight);
}else{
bctx.clearRect(0,0,sourceWidth,sourceHeight);
bctx.drawImage(oc,0,0,sourceWidth<<1,sourceHeight<<1,0,0,sourceWidth,sourceHeight);
}
}
console.log(sourceWidth);
ctx.drawImage(i==0?img[0]:i%2==0?bc:oc,0,0,sourceWidth,sourceHeight,0,0,targetWidth,targetHeight);
});