Last active
January 2, 2019 04:01
-
-
Save malipetek/2da8428fcbffe59383af478613bf62c5 to your computer and use it in GitHub Desktop.
export canvas after shrinking to a size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {!HTMLCanvasElement} canvas | |
* @param {!Number|('b'|'kb'|'mb'|'gb')} targetSize | |
* @param {?{type: ('image/png'|'image/jpeg'), jpegQuality: Number, shrinkPercentOfOriginal: Number}} options | |
*/ | |
function toDataURLwithLimit(canvas, targetSize, options){ | |
options = options || {}; | |
options.type = options.type || 'image/jpeg'; | |
options.jpegQuality = options.jpegQuality || .75; | |
options.shrinkPercentOfOriginal = options.shrinkPercentOfOriginal || 10; | |
var decrement = options.shrinkPercentOfOriginal / 100; | |
//parse size | |
if(!targetSize || !canvas){ throw new Error('Some arguments are wrong or missing'); } | |
var unit = ''; | |
if(!isNaN(targetSize)){ | |
unit = 'size'; | |
}else{ | |
var unit = (targetSize.match(/b|kb|mb|gb/gi) || [false])[0]; | |
if(!unit){ throw new Error('Unknown unit: Use "b", "kb", "mb" or "gb".'); } | |
var tSize = (targetSize.match(/\d+/gi) || [false])[0]; | |
if(!tSize){ throw new Error('Unknown size: target size has to have a number'); } | |
} | |
switch(unit){ | |
case 'b': | |
tSize = (tSize * (4 / 3)); | |
break; | |
case 'kb': | |
tSize = (tSize * (4 / 3)) * 1000; | |
break; | |
case 'mb': | |
tSize = (tSize * (4 / 3)) * 1000000; | |
break; | |
case 'gb': | |
tSize = (tSize * (4 / 3)) * 1000000000; | |
break; | |
} | |
function sizeO(s){ | |
return { | |
size: s, | |
b: s * (3 / 4), | |
kb: s * (3 / 4) / 1000, | |
mb: s * (3 / 4) / 1000000, | |
gb: s * (3 / 4) / 1000000000 | |
} | |
} | |
tSize = sizeO(tSize); | |
function act(rto){ | |
rto -= decrement; | |
var src = resize(rto); | |
var sizes = sizeO(src.length); | |
if (sizes[unit] < tSize[unit] || rto == decrement){ | |
return src; | |
}else{ | |
return act(rto); | |
} | |
} | |
function resize(r){ | |
var rcvs = document.createElement('canvas'); | |
rctx = rcvs.getContext('2d'); | |
rcvs.width = canvas.width * r; | |
rcvs.height = canvas.height * r; | |
rctx.drawImage(canvas, 0, 0, rcvs.width, rcvs.height); | |
return rcvs.toDataURL(options.type, options.jpegQuality); | |
} | |
return act(1 + decrement); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment