Skip to content

Instantly share code, notes, and snippets.

@redgoose-dev
Last active November 10, 2016 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redgoose-dev/132e3e34f35dc36d77dca758350d9c2c to your computer and use it in GitHub Desktop.
Save redgoose-dev/132e3e34f35dc36d77dca758350d9c2c to your computer and use it in GitHub Desktop.
Resize image in canvas
function log(o) {console.log(o);}
function Canvas(width, height, bgColor)
{
this.el = document.createElement('canvas');
this.ctx = this.el.getContext('2d');
var size = {
width : (width) ? width : 150,
height : (height) ? height : 100
};
this.el.width = size.width;
this.el.height = size.height;
if (bgColor)
{
this.ctx.fillStyle = bgColor;
this.ctx.fillRect(0, 0, size.width, size.height);
}
}
// function getRatio(w, h)
// {
// var result = parseInt(w) / parseInt(h);
// result = Math.round(result * 1000) / 1000;
// return result;
// }
function loadImage(src)
{
var image = new Image();
image.onload = function()
{
var targetWidth = 300;
var realSize = { width: image.naturalWidth, height: image.naturalHeight };
var targetRatio = realSize.width / targetWidth;
var targetSize = {
width : realSize.width / targetRatio,
height : realSize.height / targetRatio
};
makeImage({
image : image,
resampleCount : 2,
width : targetSize.width,
height : targetSize.height,
cx : 0,
cy : 0,
cw : realSize.width,
ch : realSize.height,
dx : 0,
dy : 0,
bgColor : '#eeeeee'
}, function(canvas){
document.body.appendChild(canvas.el);
});
};
image.src = src;
}
function makeImage(options, callback)
{
// set limit resampling count
options.resampleCount = (options.resampleCount > 1) ? options.resampleCount : 1;
options.resampleCount = (options.resampleCount < 4) ? options.resampleCount : 4;
var resampleMax = Math.pow(2, options.resampleCount);
var canvas = new Canvas(options.width * resampleMax, options.height * resampleMax, options.bgColor);
// resize canvas
var resizeCanvas = function(count, parentCanvas)
{
var max = Math.pow(2, count);
var canvasForResize = new Canvas(options.width * max, options.height * max, options.bgColor);
canvasForResize.ctx.drawImage(parentCanvas.el, 0, 0, parentCanvas.el.width * 0.5, parentCanvas.el.height * 0.5);
if (count > 0)
{
resizeCanvas(count-1, canvasForResize);
}
else
{
if (callback)
{
callback(canvasForResize);
}
}
};
// init draw image
canvas.ctx.drawImage(
options.image,
options.cx, // crop x
options.cy, // crop y
options.cw, // crop x2
options.ch, // cropy2
options.dx, // x
options.dy, // y
(options.width * resampleMax), // dw
(options.width * resampleMax) // dh
);
resizeCanvas(options.resampleCount - 1, canvas);
}
loadImage('./img/rg3242.jpg');
// working ing...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment