Socket
Socket
Sign inDemoInstall

canvas-size

Package Overview
Dependencies
0
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.2.6 to 2.0.0

369

dist/canvas-size.esm.js
/*!
* canvas-size
* v1.2.6
* v2.0.0
* https://github.com/jhildenbiddle/canvas-size
* (c) 2015-2023 John Hildenbiddle <http://hildenbiddle.com>
* (c) 2015-2024 John Hildenbiddle <http://hildenbiddle.com>
* MIT license
*/
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (;!(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) ;
} catch (err) {
_d = !0, _e = err;
} finally {
try {
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
} finally {
if (_d) throw _e;
}
}
return _arr;
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter((function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
}))), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach((function(key) {
_defineProperty(target, key, source[key]);
})) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach((function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
}));
}
return target;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function canvasTest(settings) {
var size = settings.sizes.shift();
var width = Math.max(Math.ceil(size[0]), 1);
var height = Math.max(Math.ceil(size[1]), 1);
var fill = [ width - 1, height - 1, 1, 1 ];
var job = Date.now();
var isWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
var cropCvs, testCvs;
const size = settings.sizes.shift();
const width = Math.max(Math.ceil(size[0]), 1);
const height = Math.max(Math.ceil(size[1]), 1);
const fill = [ width - 1, height - 1, 1, 1 ];
const testTimeStart = performance.now();
const isWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
let cropCvs, testCvs;
if (isWorker) {

@@ -175,4 +27,4 @@ cropCvs = new OffscreenCanvas(1, 1);

}
var cropCtx = cropCvs.getContext("2d");
var testCtx = testCvs.getContext("2d");
const cropCtx = cropCvs.getContext("2d");
const testCtx = testCvs.getContext("2d");
if (testCtx) {

@@ -182,5 +34,5 @@ testCtx.fillRect.apply(testCtx, fill);

}
var isTestPass = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data[3] !== 0;
var benchmark = Date.now() - job;
[ cropCvs, testCvs ].forEach((function(cvs) {
const isTestPass = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data[3] !== 0;
const testTime = parseInt(performance.now() - testTimeStart);
[ cropCvs, testCvs ].forEach((cvs => {
cvs.height = 0;

@@ -193,14 +45,26 @@ cvs.width = 0;

height: height,
benchmark: benchmark,
testTime: testTime,
isTestPass: isTestPass
});
if (!isTestPass && settings.sizes.length) {
canvasTest(settings);
setTimeout((() => {
canvasTest(settings);
}), 0);
}
} else if (isTestPass) {
settings.onSuccess(width, height, benchmark);
settings.onSuccess({
width: width,
height: height,
testTime: testTime
});
} else {
settings.onError(width, height, benchmark);
settings.onError({
width: width,
height: height,
testTime: testTime
});
if (settings.sizes.length) {
canvasTest(settings);
setTimeout((() => {
canvasTest(settings);
}), 0);
}

@@ -211,3 +75,3 @@ }

var testSizes = {
const testSizes = {
area: [ 16384, 14188, 11402, 11180, 10836, 8192, 4096, 1 ],

@@ -218,5 +82,3 @@ height: [ 8388607, 65535, 32767, 16384, 8192, 4096, 1 ],

var _excluded = [ "onError", "onSuccess" ];
var defaults = {
const defaults = {
max: null,

@@ -226,3 +88,2 @@ min: 1,

step: 1024,
usePromise: false,
useWorker: false,

@@ -233,22 +94,22 @@ onError: Function.prototype,

var workerJobs = {};
const workerJobs = {};
function createSizesArray(settings) {
var isArea = settings.width === settings.height;
var isWidth = settings.height === 1;
var isHeight = settings.width === 1;
var sizes = [];
const isArea = settings.width === settings.height;
const isWidth = settings.height === 1;
const isHeight = settings.width === 1;
const sizes = [];
if (!settings.width || !settings.height) {
settings.sizes.forEach((function(testSize) {
var width = isArea || isWidth ? testSize : 1;
var height = isArea || isHeight ? testSize : 1;
settings.sizes.forEach((testSize => {
const width = isArea || isWidth ? testSize : 1;
const height = isArea || isHeight ? testSize : 1;
sizes.push([ width, height ]);
}));
} else {
var testMin = settings.min || defaults.min;
var testStep = settings.step || defaults.step;
var testSize = Math.max(settings.width, settings.height);
const testMin = settings.min || defaults.min;
const testStep = settings.step || defaults.step;
let testSize = Math.max(settings.width, settings.height);
while (testSize >= testMin) {
var width = isArea || isWidth ? testSize : 1;
var height = isArea || isHeight ? testSize : 1;
const width = isArea || isWidth ? testSize : 1;
const height = isArea || isHeight ? testSize : 1;
sizes.push([ width, height ]);

@@ -262,7 +123,11 @@ testSize -= testStep;

function handleMethod(settings) {
var hasCanvasSupport = window && "HTMLCanvasElement" in window;
var hasOffscreenCanvasSupport = window && "OffscreenCanvas" in window;
var jobID = Date.now();
var _onError = settings.onError, _onSuccess = settings.onSuccess, settingsWithoutCallbacks = _objectWithoutProperties(settings, _excluded);
var worker = null;
const isBrowser = typeof window !== "undefined";
const hasPromiseSupport = isBrowser && "Promise" in window;
const hasCanvasSupport = isBrowser && "HTMLCanvasElement" in window;
const hasOffscreenCanvasSupport = isBrowser && "OffscreenCanvas" in window;
const jobID = URL.createObjectURL(new Blob([])).slice(-36);
const totalTimeStart = performance.now();
const {onError: onError, onSuccess: onSuccess, ...settingsWithoutCallbacks} = settings;
const getTotalTime = () => parseInt(performance.now() - totalTimeStart);
let worker = null;
if (!hasCanvasSupport) {

@@ -272,50 +137,69 @@ return false;

if (settings.useWorker && hasOffscreenCanvasSupport) {
var js = "\n var canvasTest = ".concat(canvasTest.toString(), ";\n onmessage = function(e) {\n canvasTest(e.data);\n };\n ");
var blob = new Blob([ js ], {
const js = `\n var canvasTest = ${canvasTest.toString()};\n onmessage = function(e) {\n canvasTest(e.data);\n };\n `;
const blob = new Blob([ js ], {
type: "application/javascript"
});
var blobURL = URL.createObjectURL(blob);
const blobURL = URL.createObjectURL(blob);
worker = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
worker.onmessage = function(e) {
var _e$data = e.data, width = _e$data.width, height = _e$data.height, benchmark = _e$data.benchmark, isTestPass = _e$data.isTestPass;
const {width: width, height: height, testTime: testTime, isTestPass: isTestPass} = e.data;
const results = {
width: width,
height: height,
testTime: testTime,
totalTime: getTotalTime()
};
if (isTestPass) {
workerJobs[jobID].onSuccess(width, height, benchmark);
workerJobs[jobID].onSuccess(results);
delete workerJobs[jobID];
} else {
workerJobs[jobID].onError(width, height, benchmark);
workerJobs[jobID].onError(results);
}
};
}
if (settings.usePromise) {
return new Promise((function(resolve, reject) {
var promiseSettings = _objectSpread2(_objectSpread2({}, settings), {}, {
onError: function onError(width, height, benchmark) {
var isLastTest;
if (hasPromiseSupport) {
return new Promise((resolve => {
const promiseSettings = {
...settings,
onError(_ref) {
let {width: width, height: height, testTime: testTime} = _ref;
const results = {
width: width,
height: height,
testTime: testTime,
totalTime: getTotalTime()
};
let isLastTest;
if (settings.sizes.length === 0) {
isLastTest = true;
} else {
var _settings$sizes$slice = settings.sizes.slice(-1), _settings$sizes$slice2 = _slicedToArray(_settings$sizes$slice, 1), _settings$sizes$slice3 = _slicedToArray(_settings$sizes$slice2[0], 2), lastWidth = _settings$sizes$slice3[0], lastHeight = _settings$sizes$slice3[1];
const [[lastWidth, lastHeight]] = settings.sizes.slice(-1);
isLastTest = width === lastWidth && height === lastHeight;
}
_onError(width, height, benchmark);
onError(results);
if (isLastTest) {
reject({
width: width,
height: height,
benchmark: benchmark
resolve({
...results,
success: false
});
}
},
onSuccess: function onSuccess(width, height, benchmark) {
_onSuccess(width, height, benchmark);
resolve({
onSuccess(_ref2) {
let {width: width, height: height, testTime: testTime} = _ref2;
const results = {
width: width,
height: height,
benchmark: benchmark
testTime: testTime,
totalTime: getTotalTime()
};
onSuccess(results);
resolve({
...results,
success: true
});
}
});
};
if (worker) {
var onError = promiseSettings.onError, onSuccess = promiseSettings.onSuccess;
const {onError: onError, onSuccess: onSuccess} = promiseSettings;
workerJobs[jobID] = {

@@ -333,4 +217,4 @@ onError: onError,

workerJobs[jobID] = {
onError: _onError,
onSuccess: _onSuccess
onError: onError,
onSuccess: onSuccess
};

@@ -344,6 +228,6 @@ worker.postMessage(settingsWithoutCallbacks);

var canvasSize = {
maxArea: function maxArea() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var sizes = createSizesArray({
const canvasSize = {
maxArea() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const sizes = createSizesArray({
width: options.max,

@@ -353,12 +237,14 @@ height: options.max,

step: options.step,
sizes: _toConsumableArray(testSizes.area)
sizes: [ ...testSizes.area ]
});
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
const settings = {
...defaults,
...options,
sizes: sizes
});
};
return handleMethod(settings);
},
maxHeight: function maxHeight() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var sizes = createSizesArray({
maxHeight() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const sizes = createSizesArray({
width: 1,

@@ -368,12 +254,14 @@ height: options.max,

step: options.step,
sizes: _toConsumableArray(testSizes.height)
sizes: [ ...testSizes.height ]
});
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
const settings = {
...defaults,
...options,
sizes: sizes
});
};
return handleMethod(settings);
},
maxWidth: function maxWidth() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var sizes = createSizesArray({
maxWidth() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const sizes = createSizesArray({
width: options.max,

@@ -383,13 +271,18 @@ height: 1,

step: options.step,
sizes: _toConsumableArray(testSizes.width)
sizes: [ ...testSizes.width ]
});
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
const settings = {
...defaults,
...options,
sizes: sizes
});
};
return handleMethod(settings);
},
test: function test() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var settings = _objectSpread2(_objectSpread2({}, defaults), options);
settings.sizes = _toConsumableArray(settings.sizes);
test() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const settings = {
...defaults,
...options
};
settings.sizes = [ ...settings.sizes ];
if (settings.width && settings.height) {

@@ -396,0 +289,0 @@ settings.sizes = [ [ settings.width, settings.height ] ];

/*!
* canvas-size
* v1.2.6
* v2.0.0
* https://github.com/jhildenbiddle/canvas-size
* (c) 2015-2023 John Hildenbiddle <http://hildenbiddle.com>
* (c) 2015-2024 John Hildenbiddle <http://hildenbiddle.com>
* MIT license
*/
function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}(e,t)||a(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||a(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){if(e){if("string"==typeof e)return s(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function c(e){var t,r,n=e.sizes.shift(),i=Math.max(Math.ceil(n[0]),1),o=Math.max(Math.ceil(n[1]),1),a=[i-1,o-1,1,1],s=Date.now(),u="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;u?(t=new OffscreenCanvas(1,1),r=new OffscreenCanvas(i,o)):((t=document.createElement("canvas")).width=1,t.height=1,(r=document.createElement("canvas")).width=i,r.height=o);var l=t.getContext("2d"),f=r.getContext("2d");f&&(f.fillRect.apply(f,a),l.drawImage(r,i-1,o-1,1,1,0,0,1,1));var h=l&&0!==l.getImageData(0,0,1,1).data[3],p=Date.now()-s;return[t,r].forEach((function(e){e.height=0,e.width=0})),u?(postMessage({width:i,height:o,benchmark:p,isTestPass:h}),!h&&e.sizes.length&&c(e)):h?e.onSuccess(i,o,p):(e.onError(i,o,p),e.sizes.length&&c(e)),h}var u={area:[16384,14188,11402,11180,10836,8192,4096,1],height:[8388607,65535,32767,16384,8192,4096,1],width:[4194303,65535,32767,16384,8192,4096,1]},l=["onError","onSuccess"],f={max:null,min:1,sizes:[],step:1024,usePromise:!1,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},h={};function p(e){var t=e.width===e.height,r=1===e.height,n=1===e.width,i=[];if(e.width&&e.height)for(var o=e.min||f.min,a=e.step||f.step,s=Math.max(e.width,e.height);s>=o;){var c=t||r?s:1,u=t||n?s:1;i.push([c,u]),s-=a}else e.sizes.forEach((function(e){var o=t||r?e:1,a=t||n?e:1;i.push([o,a])}));return i}function m(e){var r=window&&"HTMLCanvasElement"in window,o=window&&"OffscreenCanvas"in window,a=Date.now(),s=e.onError,u=e.onSuccess,f=n(e,l),p=null;if(!r)return!1;if(e.useWorker&&o){var m="\n var canvasTest = ".concat(c.toString(),";\n onmessage = function(e) {\n canvasTest(e.data);\n };\n "),d=new Blob([m],{type:"application/javascript"}),v=URL.createObjectURL(d);p=new Worker(v),URL.revokeObjectURL(v),p.onmessage=function(e){var t=e.data,r=t.width,n=t.height,i=t.benchmark;t.isTestPass?(h[a].onSuccess(r,n,i),delete h[a]):h[a].onError(r,n,i)}}return e.usePromise?new Promise((function(r,n){var o=t(t({},e),{},{onError:function(t,r,o){var a;if(0===e.sizes.length)a=!0;else{var c=i(e.sizes.slice(-1),1),u=i(c[0],2),l=u[0],f=u[1];a=t===l&&r===f}s(t,r,o),a&&n({width:t,height:r,benchmark:o})},onSuccess:function(e,t,n){u(e,t,n),r({width:e,height:t,benchmark:n})}});if(p){var l=o.onError,m=o.onSuccess;h[a]={onError:l,onSuccess:m},p.postMessage(f)}else c(o)})):p?(h[a]={onError:s,onSuccess:u},void p.postMessage(f)):c(e)}var d={maxArea:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=p({width:e.max,height:e.max,min:e.min,step:e.step,sizes:o(u.area)});return m(t(t(t({},f),e),{},{sizes:r}))},maxHeight:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=p({width:1,height:e.max,min:e.min,step:e.step,sizes:o(u.height)});return m(t(t(t({},f),e),{},{sizes:r}))},maxWidth:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=p({width:e.max,height:1,min:e.min,step:e.step,sizes:o(u.width)});return m(t(t(t({},f),e),{},{sizes:r}))},test:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t(t({},f),e);return r.sizes=o(r.sizes),r.width&&r.height&&(r.sizes=[[r.width,r.height]]),m(r)}};export{d as default};
function e(t){const s=t.sizes.shift(),n=Math.max(Math.ceil(s[0]),1),i=Math.max(Math.ceil(s[1]),1),o=[n-1,i-1,1,1],h=performance.now(),r="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;let a,c;r?(a=new OffscreenCanvas(1,1),c=new OffscreenCanvas(n,i)):(a=document.createElement("canvas"),a.width=1,a.height=1,c=document.createElement("canvas"),c.width=n,c.height=i);const m=a.getContext("2d"),d=c.getContext("2d");d&&(d.fillRect.apply(d,o),m.drawImage(c,n-1,i-1,1,1,0,0,1,1));const l=m&&0!==m.getImageData(0,0,1,1).data[3],g=parseInt(performance.now()-h);return[a,c].forEach((e=>{e.height=0,e.width=0})),r?(postMessage({width:n,height:i,testTime:g,isTestPass:l}),!l&&t.sizes.length&&setTimeout((()=>{e(t)}),0)):l?t.onSuccess({width:n,height:i,testTime:g}):(t.onError({width:n,height:i,testTime:g}),t.sizes.length&&setTimeout((()=>{e(t)}),0)),l}const t={area:[16384,14188,11402,11180,10836,8192,4096,1],height:[8388607,65535,32767,16384,8192,4096,1],width:[4194303,65535,32767,16384,8192,4096,1]},s={max:null,min:1,sizes:[],step:1024,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},n={};function i(e){const t=e.width===e.height,n=1===e.height,i=1===e.width,o=[];if(e.width&&e.height){const h=e.min||s.min,r=e.step||s.step;let a=Math.max(e.width,e.height);for(;a>=h;){const e=t||n?a:1,s=t||i?a:1;o.push([e,s]),a-=r}}else e.sizes.forEach((e=>{const s=t||n?e:1,h=t||i?e:1;o.push([s,h])}));return o}function o(t){const s="undefined"!=typeof window,i=s&&"Promise"in window,o=s&&"HTMLCanvasElement"in window,h=s&&"OffscreenCanvas"in window,r=URL.createObjectURL(new Blob([])).slice(-36),a=performance.now(),{onError:c,onSuccess:m,...d}=t,l=()=>parseInt(performance.now()-a);let g=null;if(!o)return!1;if(t.useWorker&&h){const t=`\n var canvasTest = ${e.toString()};\n onmessage = function(e) {\n canvasTest(e.data);\n };\n `,s=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(s);g=new Worker(i),URL.revokeObjectURL(i),g.onmessage=function(e){const{width:t,height:s,testTime:i,isTestPass:o}=e.data,h={width:t,height:s,testTime:i,totalTime:l()};o?(n[r].onSuccess(h),delete n[r]):n[r].onError(h)}}return i?new Promise((s=>{const i={...t,onError(e){let{width:n,height:i,testTime:o}=e;const h={width:n,height:i,testTime:o,totalTime:l()};let r;if(0===t.sizes.length)r=!0;else{const[[e,s]]=t.sizes.slice(-1);r=n===e&&i===s}c(h),r&&s({...h,success:!1})},onSuccess(e){let{width:t,height:n,testTime:i}=e;const o={width:t,height:n,testTime:i,totalTime:l()};m(o),s({...o,success:!0})}};if(g){const{onError:e,onSuccess:t}=i;n[r]={onError:e,onSuccess:t},g.postMessage(d)}else e(i)})):g?(n[r]={onError:c,onSuccess:m},void g.postMessage(d)):e(t)}const h={maxArea(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=i({width:e.max,height:e.max,min:e.min,step:e.step,sizes:[...t.area]});return o({...s,...e,sizes:n})},maxHeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=i({width:1,height:e.max,min:e.min,step:e.step,sizes:[...t.height]});return o({...s,...e,sizes:n})},maxWidth(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=i({width:e.max,height:1,min:e.min,step:e.step,sizes:[...t.width]});return o({...s,...e,sizes:n})},test(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t={...s,...e};return t.sizes=[...t.sizes],t.width&&t.height&&(t.sizes=[[t.width,t.height]]),o(t)}};export{h as default};
//# sourceMappingURL=canvas-size.esm.min.js.map
/*!
* canvas-size
* v1.2.6
* v2.0.0
* https://github.com/jhildenbiddle/canvas-size
* (c) 2015-2023 John Hildenbiddle <http://hildenbiddle.com>
* (c) 2015-2024 John Hildenbiddle <http://hildenbiddle.com>
* MIT license

@@ -13,44 +13,58 @@ */

"use strict";
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1;
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e, n, i, u, a = [], f = !0, o = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (;!(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) ;
} catch (err) {
_d = !0, _e = err;
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (;!(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) ;
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (_d) throw _e;
if (o) throw n;
}
}
return _arr;
return a;
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter((function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
}))), keys.push.apply(keys, symbols);
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter((function(r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
}))), t.push.apply(t, o);
}
return keys;
return t;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach((function(key) {
_defineProperty(target, key, source[key]);
})) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach((function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach((function(r) {
_defineProperty(e, r, t[r]);
})) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach((function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
}));
}
return target;
return e;
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : String(i);
}
function _defineProperty(obj, key, value) {

@@ -131,16 +145,2 @@ key = _toPropertyKey(key);

}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function canvasTest(settings) {

@@ -151,3 +151,3 @@ var size = settings.sizes.shift();

var fill = [ width - 1, height - 1, 1, 1 ];
var job = Date.now();
var testTimeStart = performance.now();
var isWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;

@@ -173,3 +173,3 @@ var cropCvs, testCvs;

var isTestPass = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data[3] !== 0;
var benchmark = Date.now() - job;
var testTime = parseInt(performance.now() - testTimeStart);
[ cropCvs, testCvs ].forEach((function(cvs) {

@@ -183,14 +183,26 @@ cvs.height = 0;

height: height,
benchmark: benchmark,
testTime: testTime,
isTestPass: isTestPass
});
if (!isTestPass && settings.sizes.length) {
canvasTest(settings);
setTimeout((function() {
canvasTest(settings);
}), 0);
}
} else if (isTestPass) {
settings.onSuccess(width, height, benchmark);
settings.onSuccess({
width: width,
height: height,
testTime: testTime
});
} else {
settings.onError(width, height, benchmark);
settings.onError({
width: width,
height: height,
testTime: testTime
});
if (settings.sizes.length) {
canvasTest(settings);
setTimeout((function() {
canvasTest(settings);
}), 0);
}

@@ -211,3 +223,2 @@ }

step: 1024,
usePromise: false,
useWorker: false,

@@ -243,6 +254,12 @@ onError: Function.prototype,

function handleMethod(settings) {
var hasCanvasSupport = window && "HTMLCanvasElement" in window;
var hasOffscreenCanvasSupport = window && "OffscreenCanvas" in window;
var jobID = Date.now();
var isBrowser = typeof window !== "undefined";
var hasPromiseSupport = isBrowser && "Promise" in window;
var hasCanvasSupport = isBrowser && "HTMLCanvasElement" in window;
var hasOffscreenCanvasSupport = isBrowser && "OffscreenCanvas" in window;
var jobID = URL.createObjectURL(new Blob([])).slice(-36);
var totalTimeStart = performance.now();
var _onError = settings.onError, _onSuccess = settings.onSuccess, settingsWithoutCallbacks = _objectWithoutProperties(settings, _excluded);
var getTotalTime = function getTotalTime() {
return parseInt(performance.now() - totalTimeStart);
};
var worker = null;

@@ -261,15 +278,28 @@ if (!hasCanvasSupport) {

worker.onmessage = function(e) {
var _e$data = e.data, width = _e$data.width, height = _e$data.height, benchmark = _e$data.benchmark, isTestPass = _e$data.isTestPass;
var _e$data = e.data, width = _e$data.width, height = _e$data.height, testTime = _e$data.testTime, isTestPass = _e$data.isTestPass;
var results = {
width: width,
height: height,
testTime: testTime,
totalTime: getTotalTime()
};
if (isTestPass) {
workerJobs[jobID].onSuccess(width, height, benchmark);
workerJobs[jobID].onSuccess(results);
delete workerJobs[jobID];
} else {
workerJobs[jobID].onError(width, height, benchmark);
workerJobs[jobID].onError(results);
}
};
}
if (settings.usePromise) {
return new Promise((function(resolve, reject) {
if (hasPromiseSupport) {
return new Promise((function(resolve) {
var promiseSettings = _objectSpread2(_objectSpread2({}, settings), {}, {
onError: function onError(width, height, benchmark) {
onError: function onError(_ref) {
var width = _ref.width, height = _ref.height, testTime = _ref.testTime;
var results = {
width: width,
height: height,
testTime: testTime,
totalTime: getTotalTime()
};
var isLastTest;

@@ -282,18 +312,21 @@ if (settings.sizes.length === 0) {

}
_onError(width, height, benchmark);
_onError(results);
if (isLastTest) {
reject({
width: width,
height: height,
benchmark: benchmark
});
resolve(_objectSpread2(_objectSpread2({}, results), {}, {
success: false
}));
}
},
onSuccess: function onSuccess(width, height, benchmark) {
_onSuccess(width, height, benchmark);
resolve({
onSuccess: function onSuccess(_ref2) {
var width = _ref2.width, height = _ref2.height, testTime = _ref2.testTime;
var results = {
width: width,
height: height,
benchmark: benchmark
});
testTime: testTime,
totalTime: getTotalTime()
};
_onSuccess(results);
resolve(_objectSpread2(_objectSpread2({}, results), {}, {
success: true
}));
}

@@ -300,0 +333,0 @@ });

/*!
* canvas-size
* v1.2.6
* v2.0.0
* https://github.com/jhildenbiddle/canvas-size
* (c) 2015-2023 John Hildenbiddle <http://hildenbiddle.com>
* (c) 2015-2024 John Hildenbiddle <http://hildenbiddle.com>
* MIT license
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).canvasSize=t()}(this,(function(){"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}(e,t)||a(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||a(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){if(e){if("string"==typeof e)return s(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function c(e){var t,r,n=e.sizes.shift(),i=Math.max(Math.ceil(n[0]),1),o=Math.max(Math.ceil(n[1]),1),a=[i-1,o-1,1,1],s=Date.now(),u="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;u?(t=new OffscreenCanvas(1,1),r=new OffscreenCanvas(i,o)):((t=document.createElement("canvas")).width=1,t.height=1,(r=document.createElement("canvas")).width=i,r.height=o);var l=t.getContext("2d"),f=r.getContext("2d");f&&(f.fillRect.apply(f,a),l.drawImage(r,i-1,o-1,1,1,0,0,1,1));var h=l&&0!==l.getImageData(0,0,1,1).data[3],p=Date.now()-s;return[t,r].forEach((function(e){e.height=0,e.width=0})),u?(postMessage({width:i,height:o,benchmark:p,isTestPass:h}),!h&&e.sizes.length&&c(e)):h?e.onSuccess(i,o,p):(e.onError(i,o,p),e.sizes.length&&c(e)),h}var u={area:[16384,14188,11402,11180,10836,8192,4096,1],height:[8388607,65535,32767,16384,8192,4096,1],width:[4194303,65535,32767,16384,8192,4096,1]},l=["onError","onSuccess"],f={max:null,min:1,sizes:[],step:1024,usePromise:!1,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},h={};function p(e){var t=e.width===e.height,r=1===e.height,n=1===e.width,i=[];if(e.width&&e.height)for(var o=e.min||f.min,a=e.step||f.step,s=Math.max(e.width,e.height);s>=o;){var c=t||r?s:1,u=t||n?s:1;i.push([c,u]),s-=a}else e.sizes.forEach((function(e){var o=t||r?e:1,a=t||n?e:1;i.push([o,a])}));return i}function d(e){var r=window&&"HTMLCanvasElement"in window,o=window&&"OffscreenCanvas"in window,a=Date.now(),s=e.onError,u=e.onSuccess,f=n(e,l),p=null;if(!r)return!1;if(e.useWorker&&o){var d="\n var canvasTest = ".concat(c.toString(),";\n onmessage = function(e) {\n canvasTest(e.data);\n };\n "),m=new Blob([d],{type:"application/javascript"}),v=URL.createObjectURL(m);p=new Worker(v),URL.revokeObjectURL(v),p.onmessage=function(e){var t=e.data,r=t.width,n=t.height,i=t.benchmark;t.isTestPass?(h[a].onSuccess(r,n,i),delete h[a]):h[a].onError(r,n,i)}}return e.usePromise?new Promise((function(r,n){var o=t(t({},e),{},{onError:function(t,r,o){var a;if(0===e.sizes.length)a=!0;else{var c=i(e.sizes.slice(-1),1),u=i(c[0],2),l=u[0],f=u[1];a=t===l&&r===f}s(t,r,o),a&&n({width:t,height:r,benchmark:o})},onSuccess:function(e,t,n){u(e,t,n),r({width:e,height:t,benchmark:n})}});if(p){var l=o.onError,d=o.onSuccess;h[a]={onError:l,onSuccess:d},p.postMessage(f)}else c(o)})):p?(h[a]={onError:s,onSuccess:u},void p.postMessage(f)):c(e)}var m={maxArea:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=p({width:e.max,height:e.max,min:e.min,step:e.step,sizes:o(u.area)});return d(t(t(t({},f),e),{},{sizes:r}))},maxHeight:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=p({width:1,height:e.max,min:e.min,step:e.step,sizes:o(u.height)});return d(t(t(t({},f),e),{},{sizes:r}))},maxWidth:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=p({width:e.max,height:1,min:e.min,step:e.step,sizes:o(u.width)});return d(t(t(t({},f),e),{},{sizes:r}))},test:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t(t({},f),e);return r.sizes=o(r.sizes),r.width&&r.height&&(r.sizes=[[r.width,r.height]]),d(r)}};return m}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).canvasSize=t()}(this,(function(){"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?e(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}function n(e,t,n){return(t=r(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function o(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,s,a=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw i}}return a}}(e,t)||a(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||a(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){if(e){if("string"==typeof e)return c(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function u(e){var t,r,n=e.sizes.shift(),i=Math.max(Math.ceil(n[0]),1),o=Math.max(Math.ceil(n[1]),1),s=[i-1,o-1,1,1],a=performance.now(),c="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;c?(t=new OffscreenCanvas(1,1),r=new OffscreenCanvas(i,o)):((t=document.createElement("canvas")).width=1,t.height=1,(r=document.createElement("canvas")).width=i,r.height=o);var f=t.getContext("2d"),l=r.getContext("2d");l&&(l.fillRect.apply(l,s),f.drawImage(r,i-1,o-1,1,1,0,0,1,1));var h=f&&0!==f.getImageData(0,0,1,1).data[3],m=parseInt(performance.now()-a);return[t,r].forEach((function(e){e.height=0,e.width=0})),c?(postMessage({width:i,height:o,testTime:m,isTestPass:h}),!h&&e.sizes.length&&setTimeout((function(){u(e)}),0)):h?e.onSuccess({width:i,height:o,testTime:m}):(e.onError({width:i,height:o,testTime:m}),e.sizes.length&&setTimeout((function(){u(e)}),0)),h}var f=[16384,14188,11402,11180,10836,8192,4096,1],l=[8388607,65535,32767,16384,8192,4096,1],h=[4194303,65535,32767,16384,8192,4096,1],m=["onError","onSuccess"],p={max:null,min:1,sizes:[],step:1024,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},d={};function g(e){var t=e.width===e.height,r=1===e.height,n=1===e.width,i=[];if(e.width&&e.height)for(var o=e.min||p.min,s=e.step||p.step,a=Math.max(e.width,e.height);a>=o;){var c=t||r?a:1,u=t||n?a:1;i.push([c,u]),a-=s}else e.sizes.forEach((function(e){var o=t||r?e:1,s=t||n?e:1;i.push([o,s])}));return i}function v(e){var r="undefined"!=typeof window,n=r&&"Promise"in window,s=r&&"HTMLCanvasElement"in window,a=r&&"OffscreenCanvas"in window,c=URL.createObjectURL(new Blob([])).slice(-36),f=performance.now(),l=e.onError,h=e.onSuccess,p=i(e,m),g=function(){return parseInt(performance.now()-f)},v=null;if(!s)return!1;if(e.useWorker&&a){var y="\n var canvasTest = ".concat(u.toString(),";\n onmessage = function(e) {\n canvasTest(e.data);\n };\n "),b=new Blob([y],{type:"application/javascript"}),w=URL.createObjectURL(b);v=new Worker(w),URL.revokeObjectURL(w),v.onmessage=function(e){var t=e.data,r=t.width,n=t.height,i=t.testTime,o=t.isTestPass,s={width:r,height:n,testTime:i,totalTime:g()};o?(d[c].onSuccess(s),delete d[c]):d[c].onError(s)}}return n?new Promise((function(r){var n=t(t({},e),{},{onError:function(n){var i,s=n.width,a=n.height,c={width:s,height:a,testTime:n.testTime,totalTime:g()};if(0===e.sizes.length)i=!0;else{var u=o(e.sizes.slice(-1),1),f=o(u[0],2),h=f[0],m=f[1];i=s===h&&a===m}l(c),i&&r(t(t({},c),{},{success:!1}))},onSuccess:function(e){var n={width:e.width,height:e.height,testTime:e.testTime,totalTime:g()};h(n),r(t(t({},n),{},{success:!0}))}});if(v){var i=n.onError,s=n.onSuccess;d[c]={onError:i,onSuccess:s},v.postMessage(p)}else u(n)})):v?(d[c]={onError:l,onSuccess:h},void v.postMessage(p)):u(e)}var y={maxArea:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=g({width:e.max,height:e.max,min:e.min,step:e.step,sizes:s(f)});return v(t(t(t({},p),e),{},{sizes:r}))},maxHeight:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=g({width:1,height:e.max,min:e.min,step:e.step,sizes:s(l)});return v(t(t(t({},p),e),{},{sizes:r}))},maxWidth:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=g({width:e.max,height:1,min:e.min,step:e.step,sizes:s(h)});return v(t(t(t({},p),e),{},{sizes:r}))},test:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t(t({},p),e);return r.sizes=s(r.sizes),r.width&&r.height&&(r.sizes=[[r.width,r.height]]),v(r)}};return y}));
//# sourceMappingURL=canvas-size.min.js.map
{
"name": "canvas-size",
"version": "1.2.6",
"description": "Determine the maximum size and custom dimension support of an HTML `<canvas>` element.",
"version": "2.0.0",
"description": "Determine the maximum area, height, width, and custom dimensions of an HTML canvas element.",
"author": "John Hildenbiddle <http://hildenbiddle.com>",

@@ -36,46 +36,47 @@ "license": "MIT",

],
"type": "module",
"main": "dist/canvas-size.js",
"module": "dist/canvas-size.esm.js",
"unpkg": "dist/canvas-size.min.js",
"lint-staged": {
"*.{j,t}s{x}, {c,m}js, json, html, {s}css": [
"eslint",
"prettier --write"
],
"*.md": [
"markdownlint"
]
},
"scripts": {
"prepare": "rimraf dist/*.js* && npm run build",
"prepare": "husky && rimraf dist/*.js* && npm run build",
"build": "rollup -c",
"dev": "npm start | npm run test-watch",
"lint": "eslint . && markdownlint . --ignore node_modules",
"dev": "npm start & npm run test:watch & npm run serve",
"lint": "prettier . --check && eslint . && markdownlint *.md",
"lint:fix": "prettier . --write && eslint . --fix",
"serve": "node server.js",
"start": "rimraf coverage/* && npm run build -- --watch",
"test": "rimraf coverage/* && npm run lint && karma start",
"test-watch": "npm test -- --auto-watch --no-single-run",
"test-remote": "npm test -- --remote",
"version": "npm run prepare && npm run test && git add -A dist"
"test": "rimraf coverage/* && npx playwright test",
"test:chrome": "npm test -- --project='chromium'",
"test:watch": "npm test -- --ui",
"version": "npm run prepare && npm run lint && npm run test"
},
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/plugin-proposal-object-rest-spread": "^7.12.1",
"@babel/preset-env": "^7.12.11",
"@babel/preset-env": "^7.23.9",
"@playwright/test": "^1.41.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-eslint": "^9.0.3",
"@rollup/plugin-terser": "^0.4.0",
"babel-loader": "^9.1.2",
"babel-plugin-istanbul": "^6.0.0",
"chai": "^4.2.0",
"@types/node": "^20.11.16",
"browser-sync": "^3.0.2",
"eslint": "^7.32.0",
"eslint-plugin-chai-expect": "^3.0.0",
"eslint-plugin-mocha": "^10.1.0",
"karma": "^6.3.4",
"karma-browserstack-launcher": "^1.6.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.1.0",
"karma-coverage-istanbul-reporter": "^3.0.2",
"karma-eslint": "^2.2.0",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-sourcemap-loader": "^0.4.0",
"karma-webpack": "^5.0.0",
"markdownlint-cli": "^0.33.0",
"mergician": "^1.0.2",
"mocha": "^10.2.0",
"rimraf": "^4.1.1",
"rollup": "^2.79.1",
"webpack": "^5.75.0"
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-playwright": "^0.22.2",
"husky": "^9.0.10",
"lint-staged": "^15.2.2",
"markdownlint-cli": "^0.39.0",
"mergician": "^2.0.0",
"prettier": "^3.2.5",
"rimraf": "^5.0.5",
"rollup": "^2.79.1"
}
}

@@ -11,20 +11,18 @@ # canvas-size

Determine the maximum size and custom dimension support of an HTML `<canvas>` element.
Determine the maximum area, height, width, and custom dimensions of an HTML `<canvas>` element.
- [Demo (Codesandbox)](https://on690.codesandbox.io): For modern browsers (ES6+)
- [Demo (JSBin)](https://jsbin.com/megedep/1): For legacy browsers (ES5)
- [Test Results](#test-results): HTML `<canvas>` test results for various platforms and browsers
- 🚀 [Documentation & Demo](https://jhildenbiddle.github.io/canvas-size/)
- 🔬 [Test Results](https://jhildenbiddle.github.io/canvas-size/#/?id=test-results)
## Why?
The [HTML canvas](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is [widely supported](http://caniuse.com/#feat=canvas) by modern and legacy browsers, but each browser and platform combination imposes [unique size limitations](#test-results) that will render a canvas unusable when exceeded. Unfortunately, browsers do not provide a way to determine what their limitations are, nor do they provide any kind of feedback after an unusable canvas has been created. This makes working with large canvas elements a challenge, especially for applications that support a variety of browsers and platforms.
The [HTML canvas](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is [widely supported](http://caniuse.com/#feat=canvas) by modern and legacy browsers, but each browser and platform combination imposes unique size limitations (see [Test Results](https://jhildenbiddle.github.io/canvas-size/#/?id=test-results)) that will render a canvas unusable when exceeded. Unfortunately, browsers do not provide a way to determine what their limitations are, nor do they provide any kind of feedback after an unusable canvas has been created. This makes working with large canvas elements a challenge, especially for applications that support a variety of browsers and platforms.
This micro-library provides the maximum area, height, and width of an HTML canvas element supported by the browser as well as the ability to test custom canvas dimensions. By collecting this information *before* a new canvas element is created, applications are able to reliably set canvas dimensions within the size limitations of each browser/platform.
This micro-library provides the maximum area, height, and width of an HTML canvas element supported by the browser as well as the ability to test custom canvas dimensions. By collecting this information _before_ a new canvas element is created, applications are able to reliably set canvas dimensions within the size limitations of each browser/platform.
## Features
- Determine the maximum area, height, and width of a canvas element
- Test custom canvas dimensions
- ES6 Promise support
- Web Worker and OffscreenCanvas support
- Determine the maximum `<canvas>` area, height, and width
- Test custom `<canvas>` dimensions
- Web worker + OffscreenCanvas support
- UMD and ES6 module available

@@ -35,5 +33,11 @@ - Lightweight (< 1k min+gzip) and dependency-free

| IE | Edge | Chrome | Firefox | Safari |
| ---- | ---- | ------ | ------- | ------ |
| 9+ | 12+ | 4+ | 3.6+ | 4+ |
<img src="https://raw.githubusercontent.com/jhildenbiddle/canvas-size/master/docs/assets/img/chrome.svg" valign="middle" alt="Chrome logo"> <span valign="middle">Chrome 4+</span>
<br>
<img src="https://raw.githubusercontent.com/jhildenbiddle/canvas-size/master/docs/assets/img/edge.svg" valign="middle" alt="Edge logo"> <span valign="middle">Edge 12+</span>
<br>
<img src="https://raw.githubusercontent.com/jhildenbiddle/canvas-size/master/docs/assets/img/firefox.svg" valign="middle" alt="Firefox logo"> <span valign="middle">Firefox 3.6+</span>
<br>
<img src="https://raw.githubusercontent.com/jhildenbiddle/canvas-size/master/docs/assets/img/safari.svg" valign="middle" alt="Safari logo"> <span valign="middle">Safari 4+</span>
<br>
<img src="https://raw.githubusercontent.com/jhildenbiddle/canvas-size/master/docs/assets/img/ie.svg" valign="middle" alt="Internet Explorer logo"> <span valign="middle">Internet Explorer 10+</span>

@@ -56,10 +60,13 @@ ## Installation

```js
// ES Module (latest v1.x.x)
import canvasSize from 'https://cdn.jsdelivr.net/npm/canvas-size@1/dist/canvas-size.esm.min.js';
```html
<!-- ES Module (latest v2.x.x) -->
<script
type="module"
src="https://cdn.jsdelivr.net/npm/canvas-size@2/dist/canvas-size.esm.min.js"
></script>
```
```html
<!-- Global "canvasSize" (latest v1.x.x) -->
<script src="https://cdn.jsdelivr.net/npm/canvas-size@1"></script>
<!-- Global "canvasSize" (latest v2.x.x) -->
<script src="https://cdn.jsdelivr.net/npm/canvas-size@2"></script>
```

@@ -69,360 +76,6 @@

## Usage
## Usage & Options
**Single tests**
See the [documentation site](https://jhildenbiddle.github.io/canvas-size/) for details.
Single tests return a `boolean` to indicate if the specified canvas dimensions are supported by the browser. Failed tests will return almost immediately. Successful test times are dependent upon the browser, hardware, and canvas dimensions used.
```js
var isValidCanvas = canvasSize.test({
width : 8192,
height: 8192
});
console.log(isValidCanvas); // true|false
```
**Multiple tests using callbacks**
When multiple tests are performed using `maxArea()`, `maxHeight()`, `maxWidth()`, or `test()` with multiple `sizes` defined, the `onError` callback will be invoked for each failed test until the first successful test invokes the `onSuccess` callback.
```js
canvasSize.maxArea({
onError: function(width, height, benchmark) {
console.log('Error', width, height, benchmark);
},
onSuccess: function(width, height, benchmark) {
console.log('Success', width, height, benchmark);
}
});
// Error 16387 16387 0.001
// Error 16386 16386 0.001
// Error 16385 16385 0.001
// Success 16384 16384 0.250
```
**Multiple tests using Promises**
Browsers with ES6 [Promise](https://www.google.com/search?client=safari&rls=en&q=js+promise&ie=UTF-8&oe=UTF-8) support (native or via polyfill) can set `usePromise:true` to handle test results using `promise.then()` and `promise.catch()` methods instead of using callbacks. Although promises are typically used for asynchronous tasks, canvas tests will still be synchronous when `usePromise` is `true` due to testing requirements, performance implications, and browser compatibility. For asynchronous canvas tests, see the next section.
```js
canvasSize.maxArea({
usePromise: true
})
.then(function(result) {
console.log('Success', result);
})
.catch(function(result) {
console.log('Error', result);
});
// Success { width: 16384, height: 16384, benchmark: 0.250 }
// or
// Error { width: 1, height: 1, benchmark: 0.001 }
```
**Asynchronous tests using Web Workers & OffscreenCanvas**
Browsers that support [web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) and [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/OffscreenCanvas) can set `useWorker:true` to have canvas tests performed asynchronously on a separate thread. This can prevent the browser from becoming unresponsive while testing on the browser's main thread. Browser without support for web workers and OffscreenCanvas will ignore this option and perform tests synchronously as described above.
Unfortunately, at this time [browser support for OffscreenCanvas](https://caniuse.com/#feat=offscreencanvas) is limited. In addition, canvas tests that fail immediately on the main thread can take significantly more time using the OffscreenCanvas API (most likely a bug during these early days of OffscreenCanvas support). As a result, the `useWorker` option can improve application performance by reducing the workload on the main browser thread, but doing so will result in longer test times if/when tests fail.
Note that if `useWorker` is `true` and the current browser does not support web workers and OffscreenCanvas, tests will be done on the main thread.
```js
canvasSize.maxArea({
useWorker: true,
onError(width, height, benchmark) {
console.log('Error', width, height, benchmark);
},
onSuccess(width, height, benchmark) {
console.log('Success', width, height, benchmark);
}
});
// Error 16387 16387 0.001
// Error 16386 16386 0.001
// Error 16385 16385 0.001
// Success 16384 16384 0.250
```
The `useWorker` option can be combined with the `usePromise` option as well.
```js
canvasSize.maxArea({
usePromise: true,
useWorker: true,
})
.then(function(result) {
console.log('Success', result);
})
.catch(function(result) {
console.log('Error', result);
});
// Success { width: 16384, height: 16384, benchmark: 0.250 }
// or
// Error { width: 1, height: 1, benchmark: 0.001 }
```
## Methods
### maxArea(), maxHeight(), maxWidth()
Determines the maximum area/height/width of an HTML canvas element on the client.
When `options.max` is unspecified, an optimized test will be performed using known maximum area/height/width values from previously tested browsers and platforms (see [Test Results](#test-results) for details). This will return the maximum canvas area/height/width for in the shortest amount of time.
When `options.max` is specified, the value will be used for the initial area/height/width test, then reduced by the `options.step` value for each subsequent test until a successful test occurs. This is useful for determining the maximum area/height/width of a canvas element for browser/platform combination not listed in the [Test Results](#test-results) section. Note that lower `options.step` values will provide more granular (and therefore potentially more accurate) results, but will require more time to complete due the increased number of tests that will run.
Callbacks are invoked after each test.
**Options**
- **max**: Maximum canvas height/width to test (area = max * max)
- Type: `number`
- Default: *See description above*
- **min**: Minimum canvas height/width to test (area = min * min)
- Type: `number`
- Default: `1`
- **step**: Value to subtract from test width/height after each failed test
- Type: `number`
- Default: `1024`
- **usePromise**: Determines if the method call will return an ES6 Promise. The return value for both `resolve()` and `reject()` will be an object containing `width`, `height`, and `benchmark` properties (see onError/onSuccess for value details). Requires ES6 [Promise](https://www.google.com/search?client=safari&rls=en&q=js+promise&ie=UTF-8&oe=UTF-8) support (native or via polyfill for legacy browsers).
- Type: `boolean`
- Default: `false`
- **useWorker**: Determines if canvas tests will be performed asynchronously on a separate browser thread. Requires modern browser with [web worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) support. If web worker and OffscreenCanvas support is not available, tests will be performed on the main browser thread.
- Type: `boolean`
- Default: `false`
- **onError**: Callback invoked after each unsuccessful test
- Type: `function`
- Arguments:
1. **width**: Width of canvas element (will be`1` for `maxHeight()`)
1. **height**: Height of canvas element (will be `1` for `maxWidth()`)
1. **benchmark**: Test execution time in milliseconds
- **onSuccess**: Callback invoked after each successful test
- Type: `function`
- Arguments:
1. **width**: Width of canvas element (will be`1` for `maxHeight()`)
1. **height**: Height of canvas element (will be `1` for `maxWidth()`)
1. **benchmark**: Test execution time in milliseconds
**Examples**
The following examples use `maxArea()`. Usage for `maxHeight()` and `maxWidth()` is identical.
Using callbacks:
```js
// Default (optimized sizes)
canvasSize.maxArea({
onError: function(width, height, benchmark) {
console.log('Error:', width, height, benchmark);
},
onSuccess: function(width, height, benchmark) {
console.log('Success:', width, height, benchmark);
}
});
// Custom sizes
canvasSize.maxArea({
max : 16384,
min : 1, // default
step: 1024, // default
onError: function(width, height, benchmark) {
console.log('Error:', width, height, benchmark);
},
onSuccess: function(width, height, benchmark) {
console.log('Success:', width, height, benchmark);
}
});
// Same options for maxHeight() and maxWidth()
canvasSize.maxHeight({
// ...
});
canvasSize.maxWidth({
// ...
});
```
Using ES6 Promises & Web Workers:
```js
// Default (optimized sizes)
canvasSize.maxArea({
usePromise: true,
useWorker : true,
})
.then(({ width, height, benchmark }) => {
console.log(`Success: ${width} x ${height} (${benchmark} ms)`);
})
.catch(({ width, height, benchmark }) => {
console.log(`Error: ${width} x ${height} (${benchmark} ms)`);
});
// Custom sizes
canvasSize.maxArea({
max : 16384,
min : 1, // default
step : 1024, // default
usePromise: true,
useWorker : true,
})
.then(({ width, height, benchmark }) => {
console.log(`Success: ${width} x ${height} (${benchmark} ms)`);
})
.catch(({ width, height, benchmark }) => {
console.log(`Error: ${width} x ${height} (${benchmark} ms)`);
});
// Same options for maxHeight() and maxWidth()
canvasSize.maxHeight({
// ...
});
canvasSize.maxWidth({
// ...
});
```
### test()
Determines if the dimension(s) specified exceed the HTML canvas size limitations of the browser.
To test a single dimension, use `options.width` and `options.height`. A `boolean` will be returned to indicate if the dimensions are within the browser's size limitations. To test multiple dimensions, use `options.sizes` to provide an `array` of `[width, height]` combinations to be tested (see example below). Callbacks are invoked after each test.
**Options**
- **width**: Width of the canvas to test
- Type: `number`
- **height**: Height of the canvas to test
- Type: `number`
- **sizes**: A two-dimensional array of canvas dimensions to test
- Type: `array` (see examples below)
- **usePromise**: Determines if the method call will return an ES6 Promise. The return value for both `resolve()` and `reject()` will be an object containing `width`, `height`, and `benchmark` properties (see onError/onSuccess for value details). Requires ES6 [Promise](https://www.google.com/search?client=safari&rls=en&q=js+promise&ie=UTF-8&oe=UTF-8) support (native or via polyfill for legacy browsers).
- Type: `boolean`
- Default: `false`
- **useWorker**: Determines if canvas tests will be performed asynchronously on a separate browser thread. Requires modern browser with [web worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) support. If web worker and OffscreenCanvas support is not available, tests will be performed on the main browser thread.
- Type: `boolean`
- Default: `false`
- **onError**: Callback invoked after each unsuccessful test
- Type: `function`
- Arguments:
1. **width**: width of canvas element
1. **height**: height of canvas element
1. **benchmark**: Test execution time in milliseconds
- **onSuccess**: Callback invoked after each successful test
- Type: `function`
- Arguments:
1. **width**: width of canvas element
1. **height**: height of canvas element
1. **benchmark**: Test execution time in milliseconds
**Returns**
- `boolean` when testing a single dimension. Returns `true` if the dimensions are within the browser's size limitations or `false` when exceeded.
**Examples**
Using return value:
```js
// Single dimension
var isValidCanvasSize = canvasSize.test({
height: 16384,
width : 16384
});
```
Using callbacks:
```js
// Multiple dimensions
canvasSize.test({
sizes: [
[16384, 16384],
[8192, 8192],
[4096, 4096]
],
onError: function(width, height, benchmark) {
console.log('Error:', width, height);
},
onSuccess: function(width, height, benchmark) {
console.log('Success:', width, height);
}
});
```
Using ES6 Promises & Web Workers:
```js
// Multiple dimensions
canvasSize.test({
sizes: [
[16384, 16384],
[8192, 8192],
[4096, 4096]
],
usePromise: true,
useWorker : true,
})
.then(({ width, height, benchmark }) => {
console.log(`Success: ${width} x ${height} (${benchmark} ms)`);
})
.catch(({ width, height, benchmark }) => {
console.log(`Error: ${width} x ${height} (${benchmark} ms)`);
});
```
## Test Results
Tests were conducted using virtualized device courtesy of [BrowserStack](https://www.browserstack.com/). Results may vary on actual hardware.
### Desktop
| Browser (OS) | Max Width | Max Height | Max Area (Total) |
| ------------------------ | --------: | ---------: | ----------------------------: |
| Chrome >= 73 (Mac, Win) | 65,535 | 65,535 | 16,384 x 16,384 (268,435,456) |
| Chrome <= 72 (Mac, Win) | 32,767 | 32,767 | 16,384 x 16,384 (268,435,456) |
| Edge >= 80 (Mac, Win) | 65,535 | 65,535 | 16,384 x 16,384 (268,435,456) |
| Edge <= 18 (Win) | 16,384 | 16,384 | 16,384 x 16,384 (268,435,456) |
| Firefox >= 60 (Mac, Win) | 32,767 | 32,767 | 11,180 x 11,180 (124,992,400) |
| IE 11 (Win) | 16,384 | 16,384 | 8,192 x 8,192 (67,108,864) |
| IE 9 - 10 (Win) | 8,192 | 8,192 | 8,192 x 8,192 (67,108,864) |
| Safari >= 5 (Mac) | 4,194,303 | 8,388,607 | 16,384 x 16,384 (268,435,456) |
### Mobile
Be aware that test results can vary between mobile devices running the same platform/browser combination, most notably on older devices with less capable hardware.
| Browser (OS) | Max Width | Max Height | Max Area (Total) |
| --------------------------- | --------: | ---------: | ----------------------------: |
| Chrome 91 (Android 8 - 11) | 65,535 | 65,535 | 16,384 x 16,384 (268,435,456) |
| Chrome 91 (Android 7) | 65,535 | 65,535 | 14,188 x 14,188 (201,299,344) |
| Chrome 91 (Android 6) | 65,535 | 65,535 | 16,384 x 16,384 (268,435,456) |
| Chrome 91 (Android 5) | 65,535 | 65,535 | 11,180 x 11,180 (124,992,400) |
| Chrome 68 (Android 7.1 - 9) | 32,767 | 32,767 | 14,188 x 14,188 (201,299,344) |
| Chrome 68 (Android 6) | 32,767 | 32,767 | 10,836 x 10,836 (117,418,896) |
| Chrome 68 (Android 5) | 32,767 | 32,767 | 11,402 x 11,402 (130,005,604) |
| IE (Windows Phone 8.x) | 4,096 | 4,096 | 4,096 x 4,096 (16,777,216) |
| Safari (iOS >= 9) | 4,194,303 | 8,388,607 | 4,096 x 4,096 (16,777,216) |
## Known Issues
1. **Some browsers become unresponsive during tests**
This is a result of the single-threaded nature of JavaScript and the time required to read data from large HTML canvas elements on the client. To accommodate for the brief delay that may occur when testing extremely large canvas sizes, consider the following:
- Call the library when tests are least likely to affect the overall user experience.
- [Cache test results on the client](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage) so that tests only need to be performed once per browser.
1. **Virtual environments may produce inconsistent results**
Tests conducted on virtual machines may produce results that differ from actual hardware. This is to be expected, as the virtualized hardware used in these environments can impose its own unique size limitations separate from the browser.
In some virtualized environments (mostly with older browsers), canvas-size may produce inconsistent results or fail all tests when calling `maxArea()`, `maxHeight()`, `maxWidth()`, and `test()` using `options.sizes`. This is a result of the virtual GPU failing after a test canvas exceeds the browser's size limitations, causing all subsequent tests to fail even for canvas dimensions that are actually supported by the browser. The easiest and most reliable way to address these issues is to use a GPU-optimized virtual machine. If this isn't possible and your VM only supports software rendering, avoid iterating over canvas dimensions that exceed the browser's size limitations and instead specify dimensions that are known to be supported by the browser.
## Sponsorship

@@ -429,0 +82,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc