@sanity/form-builder
Version:
Sanity form builder
115 lines (107 loc) • 2.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULT_ORIENTATION = void 0;
exports.default = orient;
var _rxjs = require("rxjs");
/* eslint-disable */
/**
* Check if we need to change dims.
*/
function rotated(n) {
return [5, 6, 7, 8].indexOf(n) > -1;
}
// Based on github.com/component/rotate
function rotate(ctx, options) {
var x = options.x;
var y = options.y;
var radians = options.degrees * (Math.PI / 180);
ctx.translate(x, y);
ctx.rotate(radians);
ctx.translate(-x, -y);
}
// Based on github.com/component/flip
function flip(canvas, x, y) {
var ctx = canvas.getContext('2d');
ctx.translate(x ? canvas.width : 0, y ? canvas.height : 0);
ctx.scale(x ? -1 : 1, y ? -1 : 1);
}
var ORIENTATION_OPS = [{
op: 'none',
degrees: 0
}, {
op: 'flip-x',
degrees: 0
}, {
op: 'none',
degrees: 180
}, {
op: 'flip-y',
degrees: 0
}, {
op: 'flip-x',
degrees: 90
}, {
op: 'none',
degrees: 90
}, {
op: 'flip-x',
degrees: -90
}, {
op: 'none',
degrees: -90
}];
var ORIENTATIONS = ['top-left', 'top-right', 'bottom-right', 'bottom-left', 'left-top', 'right-top', 'right-bottom', 'left-bottom'];
var DEFAULT_ORIENTATION = 'top-left';
exports.DEFAULT_ORIENTATION = DEFAULT_ORIENTATION;
var THUMB_SIZE = 120;
// Based on github.com/component/exif-rotate
function _orient(img, orientationNumber) {
var orientation = ORIENTATION_OPS[orientationNumber - 1];
var ratio = img.height / img.width;
img.width = THUMB_SIZE / ratio;
img.height = img.width * ratio;
// canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// dims
if (rotated(orientationNumber)) {
canvas.height = img.width;
canvas.width = img.height;
} else {
canvas.width = img.width;
canvas.height = img.height;
}
// flip
if (orientation.op === 'flip-x') {
flip(canvas, true, false);
}
if (orientation.op === 'flip-y') {
flip(canvas, false, true);
}
// rotate
if (orientation.degrees) {
rotate(ctx, {
degrees: orientation.degrees,
x: canvas.width / 2,
y: canvas.height / 2
});
if (rotated(orientationNumber)) {
var d = canvas.width - canvas.height;
ctx.translate(d / 2, -d / 2);
}
}
ctx.drawImage(img, 0, 0, img.width, img.height);
return canvas;
}
/* eslint-enable */
function orient(image, orientationId) {
return new _rxjs.Observable(observer => {
// console.time('canvas to blob')
var orientation = ORIENTATIONS.indexOf(orientationId) + 1;
var canvas = _orient(image, orientation);
observer.next(canvas.toDataURL('image/jpeg', 0.1));
observer.complete();
});
}