UNPKG

@writ/utils

Version:
50 lines (43 loc) 1.85 kB
import IsImage from './is-image'; function imageCutter(src, MEASURE_SIZE = 200) { return new Promise(function (resolve, reject) { if (!IsImage(src)) { resolve(''); return; } var canvas = document.createElement('canvas'); canvas.width = MEASURE_SIZE; canvas.height = MEASURE_SIZE; canvas.style.cssText = 'position: fixed; left: 0; top: 0; width: '.concat(MEASURE_SIZE, 'px; height: ').concat(MEASURE_SIZE, 'px; z-index: 9999; display: none;'); // document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); var img = new Image(); // img.crossOrigin = 'anonymous'; img.setAttribute('crossorigin', 'anonymous'); // works for me img.onload = function () { var width = img.width, height = img.height; var drawWidth = MEASURE_SIZE; var drawHeight = MEASURE_SIZE; var offsetX = 0; var offsetY = 0; if (width < height) { drawHeight = height * (MEASURE_SIZE / width); offsetY = -(drawHeight - drawWidth) / 2; } else { drawWidth = width * (MEASURE_SIZE / height); offsetX = -(drawWidth - drawHeight) / 2; } ctx.drawImage(img, offsetX, offsetY, drawWidth, drawHeight); var dataURL = canvas.toDataURL(); // document.body.removeChild(canvas); src instanceof File ? window.URL.revokeObjectURL(img.src) : void 0; resolve(dataURL); }; img.onerror = function (err) { reject(err); }; img.src = src instanceof File ? window.URL.createObjectURL(src) : src; }); } module.exports = imageCutter;