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.1.0 to 1.2.0

8

CHANGELOG.md
# Change Log
## 1.2.0
*2020-06-18*
- Add `useWorker` option which allows canvas tests to be performed asynchronously on a separate thread (requires Web Worker and OffscreenCanvas support)
- Add "Usage" section to the documentation
- Remove `requestAnimationFrame` from canvas test loop
## 1.1.0

@@ -4,0 +12,0 @@

372

dist/canvas-size.esm.js
/*!
* canvas-size
* v1.1.0
* v1.2.0
* https://github.com/jhildenbiddle/canvas-size

@@ -8,29 +8,180 @@ * (c) 2015-2020 John Hildenbiddle <http://hildenbiddle.com>

*/
var hasCanvasSupport = window && window.HTMLCanvasElement;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var cropCvs, cropCtx, testCvs, testCtx;
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter((function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
}));
keys.push.apply(keys, symbols);
}
return keys;
}
if (hasCanvasSupport) {
cropCvs = document.createElement("canvas");
cropCtx = cropCvs.getContext("2d");
testCvs = document.createElement("canvas");
testCtx = testCvs.getContext("2d");
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach((function(key) {
_defineProperty(target, key, source[key]);
}));
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach((function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
}));
}
}
return target;
}
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" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
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 canvasTest(settings) {
if (!hasCanvasSupport) {
return false;
}
var [width, height] = settings.sizes.shift();
var size = settings.sizes.shift();
var width = size[0];
var height = size[1];
var fill = [ width - 1, height - 1, 1, 1 ];
var job = Date.now();
testCvs.width = width;
testCvs.height = height;
testCtx.fillRect.apply(testCtx, fill);
cropCvs.width = 1;
cropCvs.height = 1;
cropCtx.drawImage(testCvs, 0 - (width - 1), 0 - (height - 1));
var isTestPass = Boolean(cropCtx.getImageData(0, 0, 1, 1).data[3]);
var isWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
var cropCvs, testCvs;
if (isWorker) {
cropCvs = new OffscreenCanvas(1, 1);
testCvs = new OffscreenCanvas(width, height);
} else {
cropCvs = document.createElement("canvas");
cropCvs.width = 1;
cropCvs.height = 1;
testCvs = document.createElement("canvas");
testCvs.width = width;
testCvs.height = height;
}
var cropCtx = cropCvs.getContext("2d");
var testCtx = testCvs.getContext("2d");
if (testCtx) {
testCtx.fillRect.apply(testCtx, fill);
cropCtx.drawImage(testCvs, width - 1, height - 1, 1, 1, 0, 0, 1, 1);
}
var isTestPass = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data[3] !== 0;
var benchmark = Date.now() - job;
if (isTestPass) {
if (isWorker) {
postMessage({
width: width,
height: height,
benchmark: benchmark,
isTestPass: isTestPass
});
if (!isTestPass && settings.sizes.length) {
canvasTest(settings);
}
} else if (isTestPass) {
settings.onSuccess(width, height, benchmark);

@@ -40,9 +191,3 @@ } else {

if (settings.sizes.length) {
if (window.requestAnimationFrame) {
window.requestAnimationFrame(() => {
canvasTest(settings);
});
} else {
canvasTest(settings);
}
canvasTest(settings);
}

@@ -53,31 +198,7 @@ }

function canvasTestPromise(settings) {
return new Promise((resolve, reject) => {
var newSettings = Object.assign({}, settings, {
onError(width, height, benchmark) {
if (settings.onError) {
settings.onError(width, height, benchmark);
}
if (settings.sizes.length === 0) {
reject({
width: width,
height: height,
benchmark: benchmark
});
}
},
onSuccess(width, height, benchmark) {
if (settings.onSuccess) {
settings.onSuccess(width, height, benchmark);
}
resolve({
width: width,
height: height,
benchmark: benchmark
});
}
});
canvasTest(newSettings);
});
}
var testSizes = {
area: [ 16384, 14188, 11402, 10836, 11180, 8192, 4096, 1 ],
height: [ 8388607, 65535, 32767, 16384, 8192, 4096, 1 ],
width: [ 4194303, 65535, 32767, 16384, 8192, 4096, 1 ]
};

@@ -90,2 +211,3 @@ var defaults = {

usePromise: false,
useWorker: false,
onError: Function.prototype,

@@ -95,7 +217,3 @@ onSuccess: Function.prototype

var testSizes = {
area: [ 32767, 16384, 14188, 11402, 10836, 11180, 8192, 4096, defaults.min ],
height: [ 8388607, 65535, 32767, 16384, 8192, 4096, defaults.min ],
width: [ 4194303, 65535, 32767, 16384, 8192, 4096, defaults.min ]
};
var workerJobs = {};

@@ -108,7 +226,7 @@ function createSizesArray(settings) {

if (!settings.width || !settings.height) {
settings.sizes.forEach(testSize => {
settings.sizes.forEach((function(testSize) {
var width = isArea || isWidth ? testSize : 1;
var height = isArea || isHeight ? testSize : 1;
sizes.push([ width, height ]);
});
}));
} else {

@@ -128,4 +246,84 @@ var testMin = settings.min || defaults.min;

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, [ "onError", "onSuccess" ]);
var worker = null;
if (!hasCanvasSupport) {
return false;
}
if (settings.useWorker && hasOffscreenCanvasSupport) {
var js = "\n ".concat(canvasTest.toString(), "\n onmessage = function(e) {\n canvasTest(e.data);\n };\n ");
var blob = new Blob([ js ], {
type: "application/javascript"
});
var 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;
if (isTestPass) {
workerJobs[jobID].onSuccess(width, height, benchmark);
delete workerJobs[jobID];
} else {
workerJobs[jobID].onError(width, height, benchmark);
}
};
}
if (settings.usePromise) {
return new Promise((function(resolve, reject) {
var promiseSettings = _objectSpread2(_objectSpread2({}, settings), {}, {
onError: function onError(width, height, benchmark) {
var 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];
isLastTest = width === lastWidth && height === lastHeight;
}
_onError(width, height, benchmark);
if (isLastTest) {
reject({
width: width,
height: height,
benchmark: benchmark
});
}
},
onSuccess: function onSuccess(width, height, benchmark) {
_onSuccess(width, height, benchmark);
resolve({
width: width,
height: height,
benchmark: benchmark
});
}
});
if (worker) {
var onError = promiseSettings.onError, onSuccess = promiseSettings.onSuccess;
workerJobs[jobID] = {
onError: onError,
onSuccess: onSuccess
};
worker.postMessage(settingsWithoutCallbacks);
} else {
canvasTest(promiseSettings);
}
}));
} else {
if (worker) {
workerJobs[jobID] = {
onError: _onError,
onSuccess: _onSuccess
};
worker.postMessage(settingsWithoutCallbacks);
} else {
return canvasTest(settings);
}
}
}
var canvasSize = {
maxArea() {
maxArea: function maxArea() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

@@ -137,14 +335,10 @@ var sizes = createSizesArray({

step: options.step,
sizes: [ ...testSizes.area ]
sizes: _toConsumableArray(testSizes.area)
});
var settings = Object.assign({}, defaults, options, {
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
if (settings.usePromise) {
return canvasTestPromise(settings);
} else {
canvasTest(settings);
}
return handleMethod(settings);
},
maxHeight() {
maxHeight: function maxHeight() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

@@ -156,14 +350,10 @@ var sizes = createSizesArray({

step: options.step,
sizes: [ ...testSizes.height ]
sizes: _toConsumableArray(testSizes.height)
});
var settings = Object.assign({}, defaults, options, {
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
if (settings.usePromise) {
return canvasTestPromise(settings);
} else {
canvasTest(settings);
}
return handleMethod(settings);
},
maxWidth() {
maxWidth: function maxWidth() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

@@ -175,25 +365,17 @@ var sizes = createSizesArray({

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

@@ -200,0 +382,0 @@ };

/*!
* canvas-size
* v1.1.0
* v1.2.0
* https://github.com/jhildenbiddle/canvas-size

@@ -8,3 +8,3 @@ * (c) 2015-2020 John Hildenbiddle <http://hildenbiddle.com>

*/
var e,t,i,s,n=window&&window.HTMLCanvasElement;function r(a){if(!n)return!1;var[h,o]=a.sizes.shift(),m=[h-1,o-1,1,1],g=Date.now();i.width=h,i.height=o,s.fillRect.apply(s,m),e.width=1,e.height=1,t.drawImage(i,0-(h-1),0-(o-1));var d=Boolean(t.getImageData(0,0,1,1).data[3]),u=Date.now()-g;return d?a.onSuccess(h,o,u):(a.onError(h,o,u),a.sizes.length&&(window.requestAnimationFrame?window.requestAnimationFrame(()=>{r(a)}):r(a))),d}function a(e){return new Promise((t,i)=>{r(Object.assign({},e,{onError(t,s,n){e.onError&&e.onError(t,s,n),0===e.sizes.length&&i({width:t,height:s,benchmark:n})},onSuccess(i,s,n){e.onSuccess&&e.onSuccess(i,s,n),t({width:i,height:s,benchmark:n})}}))})}n&&(e=document.createElement("canvas"),t=e.getContext("2d"),i=document.createElement("canvas"),s=i.getContext("2d"));var h={max:null,min:1,sizes:[],step:1024,usePromise:!1,onError:Function.prototype,onSuccess:Function.prototype},o={area:[32767,16384,14188,11402,10836,11180,8192,4096,h.min],height:[8388607,65535,32767,16384,8192,4096,h.min],width:[4194303,65535,32767,16384,8192,4096,h.min]};function m(e){var t=e.width===e.height,i=1===e.height,s=1===e.width,n=[];if(e.width&&e.height)for(var r=e.min||h.min,a=e.step||h.step,o=Math.max(e.width,e.height);o>=r;){var m=t||i?o:1,g=t||s?o:1;n.push([m,g]),o-=a}else e.sizes.forEach(e=>{var r=t||i?e:1,a=t||s?e:1;n.push([r,a])});return n}var g={maxArea(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m({width:e.max,height:e.max,min:e.min,step:e.step,sizes:[...o.area]}),i=Object.assign({},h,e,{sizes:t});if(i.usePromise)return a(i);r(i)},maxHeight(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m({width:1,height:e.max,min:e.min,step:e.step,sizes:[...o.height]}),i=Object.assign({},h,e,{sizes:t});if(i.usePromise)return a(i);r(i)},maxWidth(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m({width:e.max,height:1,min:e.min,step:e.step,sizes:[...o.width]}),i=Object.assign({},h,e,{sizes:t});if(i.usePromise)return a(i);r(i)},test(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=Object.assign({},h,e);return t.sizes=[...t.sizes],t.width&&t.height&&(t.sizes=[[t.width,t.height]]),t.usePromise?a(t):r(t)}};export default g;
function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(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 r(r){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?t(Object(o),!0).forEach((function(t){e(r,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(o)):t(Object(o)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(o,e))}))}return r}function n(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function o(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var r=[],n=!0,o=!1,i=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){o=!0,i=e}finally{try{n||null==s.return||s.return()}finally{if(o)throw i}}return r}(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 i(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))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(),o=n[0],i=n[1],a=[o-1,i-1,1,1],s=Date.now(),u="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;u?(t=new OffscreenCanvas(1,1),r=new OffscreenCanvas(o,i)):((t=document.createElement("canvas")).width=1,t.height=1,(r=document.createElement("canvas")).width=o,r.height=i);var f=t.getContext("2d"),l=r.getContext("2d");l&&(l.fillRect.apply(l,a),f.drawImage(r,o-1,i-1,1,1,0,0,1,1));var h=f&&0!==f.getImageData(0,0,1,1).data[3],p=Date.now()-s;return u?(postMessage({width:o,height:i,benchmark:p,isTestPass:h}),!h&&e.sizes.length&&c(e)):h?e.onSuccess(o,i,p):(e.onError(o,i,p),e.sizes.length&&c(e)),h}var u=[16384,14188,11402,10836,11180,8192,4096,1],f=[8388607,65535,32767,16384,8192,4096,1],l=[4194303,65535,32767,16384,8192,4096,1],h={max:null,min:1,sizes:[],step:1024,usePromise:!1,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},p={};function m(e){var t=e.width===e.height,r=1===e.height,n=1===e.width,o=[];if(e.width&&e.height)for(var i=e.min||h.min,a=e.step||h.step,s=Math.max(e.width,e.height);s>=i;){var c=t||r?s:1,u=t||n?s:1;o.push([c,u]),s-=a}else e.sizes.forEach((function(e){var i=t||r?e:1,a=t||n?e:1;o.push([i,a])}));return o}function d(e){var t=window&&"HTMLCanvasElement"in window,i=window&&"OffscreenCanvas"in window,a=Date.now(),s=e.onError,u=e.onSuccess,f=n(e,["onError","onSuccess"]),l=null;if(!t)return!1;if(e.useWorker&&i){var h="\n ".concat(c.toString(),"\n onmessage = function(e) {\n canvasTest(e.data);\n };\n "),m=new Blob([h],{type:"application/javascript"}),d=URL.createObjectURL(m);l=new Worker(d),URL.revokeObjectURL(d),l.onmessage=function(e){var t=e.data,r=t.width,n=t.height,o=t.benchmark;t.isTestPass?(p[a].onSuccess(r,n,o),delete p[a]):p[a].onError(r,n,o)}}return e.usePromise?new Promise((function(t,n){var i=r(r({},e),{},{onError:function(t,r,i){var a;if(0===e.sizes.length)a=!0;else{var c=o(e.sizes.slice(-1),1),u=o(c[0],2),f=u[0],l=u[1];a=t===f&&r===l}s(t,r,i),a&&n({width:t,height:r,benchmark:i})},onSuccess:function(e,r,n){u(e,r,n),t({width:e,height:r,benchmark:n})}});if(l){var h=i.onError,m=i.onSuccess;p[a]={onError:h,onSuccess:m},l.postMessage(f)}else c(i)})):l?(p[a]={onError:s,onSuccess:u},void l.postMessage(f)):c(e)}var b={maxArea:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m({width:e.max,height:e.max,min:e.min,step:e.step,sizes:i(u)}),n=r(r(r({},h),e),{},{sizes:t});return d(n)},maxHeight:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m({width:1,height:e.max,min:e.min,step:e.step,sizes:i(f)}),n=r(r(r({},h),e),{},{sizes:t});return d(n)},maxWidth:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m({width:e.max,height:1,min:e.min,step:e.step,sizes:i(l)}),n=r(r(r({},h),e),{},{sizes:t});return d(n)},test:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=r(r({},h),e);return t.sizes=i(t.sizes),t.width&&t.height&&(t.sizes=[[t.width,t.height]]),d(t)}};export default b;
//# sourceMappingURL=canvas-size.esm.min.js.map
/*!
* canvas-size
* v1.1.0
* v1.2.0
* https://github.com/jhildenbiddle/canvas-size

@@ -13,16 +13,70 @@ * (c) 2015-2020 John Hildenbiddle <http://hildenbiddle.com>

"use strict";
function _extends() {
_extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (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 = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach((function(key) {
_defineProperty(target, key, source[key]);
}));
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach((function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
}));
}
return target;
};
return _extends.apply(this, arguments);
}
return target;
}
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) {

@@ -85,26 +139,40 @@ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();

}
var hasCanvasSupport = window && window.HTMLCanvasElement;
var cropCvs, cropCtx, testCvs, testCtx;
if (hasCanvasSupport) {
cropCvs = document.createElement("canvas");
cropCtx = cropCvs.getContext("2d");
testCvs = document.createElement("canvas");
testCtx = testCvs.getContext("2d");
}
function canvasTest(settings) {
if (!hasCanvasSupport) {
return false;
}
var _settings$sizes$shift = settings.sizes.shift(), _settings$sizes$shift2 = _slicedToArray(_settings$sizes$shift, 2), width = _settings$sizes$shift2[0], height = _settings$sizes$shift2[1];
var size = settings.sizes.shift();
var width = size[0];
var height = size[1];
var fill = [ width - 1, height - 1, 1, 1 ];
var job = Date.now();
testCvs.width = width;
testCvs.height = height;
testCtx.fillRect.apply(testCtx, fill);
cropCvs.width = 1;
cropCvs.height = 1;
cropCtx.drawImage(testCvs, 0 - (width - 1), 0 - (height - 1));
var isTestPass = Boolean(cropCtx.getImageData(0, 0, 1, 1).data[3]);
var isWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
var cropCvs, testCvs;
if (isWorker) {
cropCvs = new OffscreenCanvas(1, 1);
testCvs = new OffscreenCanvas(width, height);
} else {
cropCvs = document.createElement("canvas");
cropCvs.width = 1;
cropCvs.height = 1;
testCvs = document.createElement("canvas");
testCvs.width = width;
testCvs.height = height;
}
var cropCtx = cropCvs.getContext("2d");
var testCtx = testCvs.getContext("2d");
if (testCtx) {
testCtx.fillRect.apply(testCtx, fill);
cropCtx.drawImage(testCvs, width - 1, height - 1, 1, 1, 0, 0, 1, 1);
}
var isTestPass = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data[3] !== 0;
var benchmark = Date.now() - job;
if (isTestPass) {
if (isWorker) {
postMessage({
width: width,
height: height,
benchmark: benchmark,
isTestPass: isTestPass
});
if (!isTestPass && settings.sizes.length) {
canvasTest(settings);
}
} else if (isTestPass) {
settings.onSuccess(width, height, benchmark);

@@ -114,9 +182,3 @@ } else {

if (settings.sizes.length) {
if (window.requestAnimationFrame) {
window.requestAnimationFrame((function() {
canvasTest(settings);
}));
} else {
canvasTest(settings);
}
canvasTest(settings);
}

@@ -126,31 +188,7 @@ }

}
function canvasTestPromise(settings) {
return new Promise((function(resolve, reject) {
var newSettings = _extends({}, settings, {
onError: function onError(width, height, benchmark) {
if (settings.onError) {
settings.onError(width, height, benchmark);
}
if (settings.sizes.length === 0) {
reject({
width: width,
height: height,
benchmark: benchmark
});
}
},
onSuccess: function onSuccess(width, height, benchmark) {
if (settings.onSuccess) {
settings.onSuccess(width, height, benchmark);
}
resolve({
width: width,
height: height,
benchmark: benchmark
});
}
});
canvasTest(newSettings);
}));
}
var testSizes = {
area: [ 16384, 14188, 11402, 10836, 11180, 8192, 4096, 1 ],
height: [ 8388607, 65535, 32767, 16384, 8192, 4096, 1 ],
width: [ 4194303, 65535, 32767, 16384, 8192, 4096, 1 ]
};
var defaults = {

@@ -162,10 +200,7 @@ max: null,

usePromise: false,
useWorker: false,
onError: Function.prototype,
onSuccess: Function.prototype
};
var testSizes = {
area: [ 32767, 16384, 14188, 11402, 10836, 11180, 8192, 4096, defaults.min ],
height: [ 8388607, 65535, 32767, 16384, 8192, 4096, defaults.min ],
width: [ 4194303, 65535, 32767, 16384, 8192, 4096, defaults.min ]
};
var workerJobs = {};
function createSizesArray(settings) {

@@ -195,2 +230,81 @@ var isArea = settings.width === settings.height;

}
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, [ "onError", "onSuccess" ]);
var worker = null;
if (!hasCanvasSupport) {
return false;
}
if (settings.useWorker && hasOffscreenCanvasSupport) {
var js = "\n ".concat(canvasTest.toString(), "\n onmessage = function(e) {\n canvasTest(e.data);\n };\n ");
var blob = new Blob([ js ], {
type: "application/javascript"
});
var 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;
if (isTestPass) {
workerJobs[jobID].onSuccess(width, height, benchmark);
delete workerJobs[jobID];
} else {
workerJobs[jobID].onError(width, height, benchmark);
}
};
}
if (settings.usePromise) {
return new Promise((function(resolve, reject) {
var promiseSettings = _objectSpread2(_objectSpread2({}, settings), {}, {
onError: function onError(width, height, benchmark) {
var 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];
isLastTest = width === lastWidth && height === lastHeight;
}
_onError(width, height, benchmark);
if (isLastTest) {
reject({
width: width,
height: height,
benchmark: benchmark
});
}
},
onSuccess: function onSuccess(width, height, benchmark) {
_onSuccess(width, height, benchmark);
resolve({
width: width,
height: height,
benchmark: benchmark
});
}
});
if (worker) {
var onError = promiseSettings.onError, onSuccess = promiseSettings.onSuccess;
workerJobs[jobID] = {
onError: onError,
onSuccess: onSuccess
};
worker.postMessage(settingsWithoutCallbacks);
} else {
canvasTest(promiseSettings);
}
}));
} else {
if (worker) {
workerJobs[jobID] = {
onError: _onError,
onSuccess: _onSuccess
};
worker.postMessage(settingsWithoutCallbacks);
} else {
return canvasTest(settings);
}
}
}
var canvasSize = {

@@ -206,10 +320,6 @@ maxArea: function maxArea() {

});
var settings = _extends({}, defaults, options, {
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
if (settings.usePromise) {
return canvasTestPromise(settings);
} else {
canvasTest(settings);
}
return handleMethod(settings);
},

@@ -225,10 +335,6 @@ maxHeight: function maxHeight() {

});
var settings = _extends({}, defaults, options, {
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
if (settings.usePromise) {
return canvasTestPromise(settings);
} else {
canvasTest(settings);
}
return handleMethod(settings);
},

@@ -244,14 +350,10 @@ maxWidth: function maxWidth() {

});
var settings = _extends({}, defaults, options, {
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
if (settings.usePromise) {
return canvasTestPromise(settings);
} else {
canvasTest(settings);
}
return handleMethod(settings);
},
test: function test() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var settings = _extends({}, defaults, options);
var settings = _objectSpread2(_objectSpread2({}, defaults), options);
settings.sizes = _toConsumableArray(settings.sizes);

@@ -261,7 +363,3 @@ if (settings.width && settings.height) {

}
if (settings.usePromise) {
return canvasTestPromise(settings);
} else {
return canvasTest(settings);
}
return handleMethod(settings);
}

@@ -268,0 +366,0 @@ };

/*!
* canvas-size
* v1.1.0
* v1.2.0
* https://github.com/jhildenbiddle/canvas-size

@@ -8,3 +8,3 @@ * (c) 2015-2020 John Hildenbiddle <http://hildenbiddle.com>

*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).canvasSize=e()}(this,(function(){"use strict";function t(){return(t=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function e(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{r||null==s.return||s.return()}finally{if(i)throw o}}return n}(t,e)||r(t,e)||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 n(t){return function(t){if(Array.isArray(t))return i(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||r(t)||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 r(t,e){if(t){if("string"==typeof t)return i(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?i(t,e):void 0}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var o,a,s,u,h=window&&window.HTMLCanvasElement;function c(t){if(!h)return!1;var n=e(t.sizes.shift(),2),r=n[0],i=n[1],f=[r-1,i-1,1,1],m=Date.now();s.width=r,s.height=i,u.fillRect.apply(u,f),o.width=1,o.height=1,a.drawImage(s,0-(r-1),0-(i-1));var d=Boolean(a.getImageData(0,0,1,1).data[3]),l=Date.now()-m;return d?t.onSuccess(r,i,l):(t.onError(r,i,l),t.sizes.length&&(window.requestAnimationFrame?window.requestAnimationFrame((function(){c(t)})):c(t))),d}function f(e){return new Promise((function(n,r){c(t({},e,{onError:function(t,n,i){e.onError&&e.onError(t,n,i),0===e.sizes.length&&r({width:t,height:n,benchmark:i})},onSuccess:function(t,r,i){e.onSuccess&&e.onSuccess(t,r,i),n({width:t,height:r,benchmark:i})}}))}))}h&&(o=document.createElement("canvas"),a=o.getContext("2d"),s=document.createElement("canvas"),u=s.getContext("2d"));var m={max:null,min:1,sizes:[],step:1024,usePromise:!1,onError:Function.prototype,onSuccess:Function.prototype},d={area:[32767,16384,14188,11402,10836,11180,8192,4096,m.min],height:[8388607,65535,32767,16384,8192,4096,m.min],width:[4194303,65535,32767,16384,8192,4096,m.min]};function l(t){var e=t.width===t.height,n=1===t.height,r=1===t.width,i=[];if(t.width&&t.height)for(var o=t.min||m.min,a=t.step||m.step,s=Math.max(t.width,t.height);s>=o;){var u=e||n?s:1,h=e||r?s:1;i.push([u,h]),s-=a}else t.sizes.forEach((function(t){var o=e||n?t:1,a=e||r?t:1;i.push([o,a])}));return i}return{maxArea:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=l({width:e.max,height:e.max,min:e.min,step:e.step,sizes:n(d.area)}),i=t({},m,e,{sizes:r});if(i.usePromise)return f(i);c(i)},maxHeight:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=l({width:1,height:e.max,min:e.min,step:e.step,sizes:n(d.height)}),i=t({},m,e,{sizes:r});if(i.usePromise)return f(i);c(i)},maxWidth:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=l({width:e.max,height:1,min:e.min,step:e.step,sizes:n(d.width)}),i=t({},m,e,{sizes:r});if(i.usePromise)return f(i);c(i)},test:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t({},m,e);return r.sizes=n(r.sizes),r.width&&r.height&&(r.sizes=[[r.width,r.height]]),r.usePromise?f(r):c(r)}}}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).canvasSize=t()}(this,(function(){"use strict";function e(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?t(Object(o),!0).forEach((function(t){e(n,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(o)):t(Object(o)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(o,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function o(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var s,a=e[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==a.return||a.return()}finally{if(o)throw i}}return n}(e,t)||s(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 i(e){return function(e){if(Array.isArray(e))return a(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||s(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 s(e,t){if(e){if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(e,t):void 0}}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function c(e){var t,n,r=e.sizes.shift(),o=r[0],i=r[1],s=[o-1,i-1,1,1],a=Date.now(),u="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;u?(t=new OffscreenCanvas(1,1),n=new OffscreenCanvas(o,i)):((t=document.createElement("canvas")).width=1,t.height=1,(n=document.createElement("canvas")).width=o,n.height=i);var f=t.getContext("2d"),l=n.getContext("2d");l&&(l.fillRect.apply(l,s),f.drawImage(n,o-1,i-1,1,1,0,0,1,1));var h=f&&0!==f.getImageData(0,0,1,1).data[3],p=Date.now()-a;return u?(postMessage({width:o,height:i,benchmark:p,isTestPass:h}),!h&&e.sizes.length&&c(e)):h?e.onSuccess(o,i,p):(e.onError(o,i,p),e.sizes.length&&c(e)),h}var u=[16384,14188,11402,10836,11180,8192,4096,1],f=[8388607,65535,32767,16384,8192,4096,1],l=[4194303,65535,32767,16384,8192,4096,1],h={max:null,min:1,sizes:[],step:1024,usePromise:!1,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},p={};function d(e){var t=e.width===e.height,n=1===e.height,r=1===e.width,o=[];if(e.width&&e.height)for(var i=e.min||h.min,s=e.step||h.step,a=Math.max(e.width,e.height);a>=i;){var c=t||n?a:1,u=t||r?a:1;o.push([c,u]),a-=s}else e.sizes.forEach((function(e){var i=t||n?e:1,s=t||r?e:1;o.push([i,s])}));return o}function m(e){var t=window&&"HTMLCanvasElement"in window,i=window&&"OffscreenCanvas"in window,s=Date.now(),a=e.onError,u=e.onSuccess,f=r(e,["onError","onSuccess"]),l=null;if(!t)return!1;if(e.useWorker&&i){var h="\n ".concat(c.toString(),"\n onmessage = function(e) {\n canvasTest(e.data);\n };\n "),d=new Blob([h],{type:"application/javascript"}),m=URL.createObjectURL(d);l=new Worker(m),URL.revokeObjectURL(m),l.onmessage=function(e){var t=e.data,n=t.width,r=t.height,o=t.benchmark;t.isTestPass?(p[s].onSuccess(n,r,o),delete p[s]):p[s].onError(n,r,o)}}return e.usePromise?new Promise((function(t,r){var i=n(n({},e),{},{onError:function(t,n,i){var s;if(0===e.sizes.length)s=!0;else{var c=o(e.sizes.slice(-1),1),u=o(c[0],2),f=u[0],l=u[1];s=t===f&&n===l}a(t,n,i),s&&r({width:t,height:n,benchmark:i})},onSuccess:function(e,n,r){u(e,n,r),t({width:e,height:n,benchmark:r})}});if(l){var h=i.onError,d=i.onSuccess;p[s]={onError:h,onSuccess:d},l.postMessage(f)}else c(i)})):l?(p[s]={onError:a,onSuccess:u},void l.postMessage(f)):c(e)}return{maxArea:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=d({width:e.max,height:e.max,min:e.min,step:e.step,sizes:i(u)}),r=n(n(n({},h),e),{},{sizes:t});return m(r)},maxHeight:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=d({width:1,height:e.max,min:e.min,step:e.step,sizes:i(f)}),r=n(n(n({},h),e),{},{sizes:t});return m(r)},maxWidth:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=d({width:e.max,height:1,min:e.min,step:e.step,sizes:i(l)}),r=n(n(n({},h),e),{},{sizes:t});return m(r)},test:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=n(n({},h),e);return t.sizes=i(t.sizes),t.width&&t.height&&(t.sizes=[[t.width,t.height]]),m(t)}}}));
//# sourceMappingURL=canvas-size.min.js.map
{
"name": "canvas-size",
"version": "1.1.0",
"version": "1.2.0",
"description": "Determine the maximum size of an HTML canvas element and test support for custom canvas dimensions.",

@@ -24,5 +24,9 @@ "author": "John Hildenbiddle <http://hildenbiddle.com>",

"offscreen",
"offscreencanvas",
"promise",
"scale",
"size",
"test",
"web worker",
"worker",
"width"

@@ -48,4 +52,3 @@ ],

"@babel/core": "^7.9.6",
"@babel/plugin-transform-object-assign": "^7.8.3",
"@babel/polyfill": "^7.8.7",
"@babel/plugin-proposal-object-rest-spread": "^7.10.1",
"@babel/preset-env": "^7.9.6",

@@ -55,6 +58,6 @@ "babel-loader": "^8.1.0",

"chai": "^4.2.0",
"eslint": "^7.1.0",
"eslint": "^7.2.0",
"eslint-plugin-chai-expect": "^2.1.0",
"eslint-plugin-mocha": "^7.0.0",
"karma": "^5.0.9",
"karma": "^5.1.0",
"karma-chai": "^0.1.0",

@@ -66,9 +69,9 @@ "karma-chrome-launcher": "^3.1.0",

"karma-mocha-reporter": "^2.2.5",
"karma-sauce-launcher": "^4.1.4",
"karma-sauce-launcher": "^4.1.5",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^4.0.2",
"lodash.merge": "^4.6.2",
"mocha": "^4.1.0",
"mocha": "^8.0.1",
"rimraf": "^3.0.2",
"rollup": "^2.10.9",
"rollup": "^2.17.0",
"rollup-plugin-babel": "^4.4.0",

@@ -75,0 +78,0 @@ "rollup-plugin-commonjs": "^10.1.0",

@@ -13,4 +13,4 @@ # canvas-size

- [Demo](https://on690.csb.app/) for modern browsers (CodeSandbox)
- [Demo](https://jsbin.com/cacatohire/2/edit?js,output) for legacy browsers (JSBin)
- [Demo](https://on690.codesandbox.io) for modern browsers (CodeSandbox)
- [Demo](https://jsbin.com/megedep/1/edit?js,output) for legacy browsers (JSBin)

@@ -20,4 +20,5 @@ ## Features

- Determine the maximum area, height, and width of a canvas element
- Test support for custom canvas element dimensions
- Optional ES6 [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) support
- Test custom canvas dimensions
- ES6 Promise support
- Web Worker and OffscreenCanvas support
- UMD and ES6 module available

@@ -36,2 +37,3 @@ - Lightweight (< 1k min+gzip) and dependency-free

- [Installation](#installation)
- [Usage](#usage)
- [Methods](#methods)

@@ -81,2 +83,101 @@ - [Test Results](#test-results)

## Usage
**Single tests**
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.
```javascript
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

@@ -109,5 +210,8 @@

- 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).
- **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

@@ -157,3 +261,3 @@ - Type: `function`

Using ES6 Promises:
Using ES6 Promises & Web Workers:

@@ -163,3 +267,4 @@ ```javascript

canvasSize.maxArea({
usePromise: true
usePromise: true,
useWorker : true,
})

@@ -178,3 +283,4 @@ .then(({ width, height, benchmark }) => {

step : 1024, // default
usePromise: true
usePromise: true,
useWorker : true,
})

@@ -203,5 +309,8 @@ .then(({ width, height, benchmark }) => {

- 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).
- **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

@@ -234,4 +343,2 @@ - Type: `function`

});
console.log(isValidCanvasSize); // true/false
```

@@ -258,3 +365,3 @@

Using ES6 Promises:
Using ES6 Promises & Web Workers:

@@ -269,3 +376,4 @@ ```javascript

]
usePromise: true
usePromise: true,
useWorker : true,
})

@@ -286,23 +394,23 @@ .then(({ width, height, benchmark }) => {

| Browser (OS) | Max Width | Max Height | Max Area (Test Size) |
| Browser (OS) | Max Width | Max Height | Max Area (Total) |
| ----------------------- | --------: | ---------: | ----------------------------: |
| Chrome 83 (Mac, Win *) | 65,535 | 65,535 | 268,435,456 (16,384 x 16,384) |
| Chrome 70 (Mac, Win *) | 32,767 | 32,767 | 268,435,456 (16,384 x 16,384) |
| Edge 17 * | 16,384 | 16,384 | 268,435,456 (16,384 x 16,384) |
| Firefox 63 (Mac, Win *) | 32,767 | 32,767 | 124,992,400 (11,180 x 11,180) |
| IE 11 * | 16,384 | 16,384 | 67,108,864 (8,192 x 8,192) |
| IE 9 - 10 * | 8,192 | 8,192 | 67,108,864 (8,192 x 8,192) |
| Safari 7 - 12 | 4,194,303 | 8,388,607 | 268,435,456 (16,384 x 16,384) |
| Chrome 83 (Mac, Win *) | 65,535 | 65,535 | 16,384 x 16,384 (268,435,456) |
| Chrome 70 (Mac, Win *) | 32,767 | 32,767 | 16,384 x 16,384 (268,435,456) |
| Edge 17 * | 16,384 | 16,384 | 16,384 x 16,384 (268,435,456) |
| Firefox 63 (Mac, Win *) | 32,767 | 32,767 | 11,180 x 11,180 (124,992,400) |
| IE 11 * | 16,384 | 16,384 | 8,192 x 8,192 (67,108,864) |
| IE 9 - 10 * | 8,192 | 8,192 | 8,192 x 8,192 (67,108,864) |
| Safari 7 - 12 | 4,194,303 | 8,388,607 | 16,384 x 16,384 (268,435,456) |
### Mobile
| Browser (OS) | Max Width | Max Height | Max Area (Test Size) |
| Browser (OS) | Max Width | Max Height | Max Area (Total) |
| ----------------------------- | --------: | ---------: | ----------------------------: |
| Chrome 68 (Android 9) * | 32,767 | 32,767 | 201,299,344 (14,188 x 14,188) |
| Chrome 68 (Android 7.1 - 8) * | 32,767 | 32,767 | 201,299,344 (14,188 x 14,188) |
| Chrome 68 (Android 6) | 32,767 | 32,767 | 117,418,896 (10,836 x 10,836) |
| Chrome 68 (Android 5) * | 32,767 | 32,767 | 130,005,604 (11,402 x 11,402) |
| Chrome 68 (Android 4.4) * | 32,767 | 32,767 | 268,435,456 (16,384 x 16,384) |
| IE (Windows Phone 8.x) | 4,096 | 4,096 | 16,777,216 (4,096 x 4,096) |
| Safari (iOS 9 - 12) | 4,194,303 | 8,388,607 | 16,777,216 (4,096 x 4,096) |
| Chrome 68 (Android 9) * | 32,767 | 32,767 | 14,188 x 14,188 (201,299,344) |
| Chrome 68 (Android 7.1 - 8) * | 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) |
| Chrome 68 (Android 4.4) * | 32,767 | 32,767 | 16,384 x 16,384 (268,435,456) |
| IE (Windows Phone 8.x) | 4,096 | 4,096 | 4,096 x 4,096 (16,777,216) |
| Safari (iOS 9 - 12) | 4,194,303 | 8,388,607 | 4,096 x 4,096 (16,777,216) |

@@ -313,6 +421,4 @@ ## Known Issues

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. [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) and [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) seem like a promising solution for supporting browsers, but extensive testing shows performance far worse than testing on the main thread.
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:
To accommodate for the brief delays 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.

@@ -323,5 +429,5 @@ - [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.

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.
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 and operating systems), 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. In these scenarios, 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. Supported dimensions can be detected manually by calling `test()` using `options.width` and `options.height`.
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.

@@ -328,0 +434,0 @@ ## Contact

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