Helper method to ensure that a canvas of a given size is usable.
ensureUsableCanvas = function(
Input canvas element. Must not be null.
The value used to scale the canvas to a usable size.
The size of usable canvas (where the whole surface area is available for drawing) depends on the current browser, operation system and video card.
For example, let us say you want to create a canvas of size 8000 by 8000 pixels. This code will almost always work - create a canvas and fill it with red:
// Create the canvas
var canvas = document.createElement("canvas");
// Set its size
canvas.width = 8000;
canvas.height = 8000;
// Get a context to it
var context = canvas.getContext("2d");
// Fill it with red
context.rect(0, 0, 8000, 8000);
context.fillStyle = "red";
However, when the image data is obtained back from the canvas, the data might be truncated and the fill operation did not cover the whole area:
// Get the last pixel as an image data
var imageData = context.getImageData(7999, 7999, 1, 1);
// Check the color
var red = imageData.data;
var green = imageData.data;
var blue = imageData.data;
console.log(red + ',' + green + ',' blue);
if(red == 0xFF && green == 0x00 && blue == 0x00)
console.log('canvas size 8000 by 8000 is usable');
console.log('canvas size 8000 by 8000 is not usable');
The value of red, green and blue is not guaranteed to be a red color. The maximum usable size depends on many combination and changes all the time with browser and video card updates. This helper method can be used to ensure that the canvas contains nothing but a usable area. If scaling is required, the canvas width and height is re-set with the new scaled value (keeping the original aspect ratio) and this scale value is returned. A return value of 1 means no scaling is required and the original size can be used. A value less than 1 means scaling is required. The scaling is performed to fit the canvas in 1K pixels decrements from the original size keeping the original aspect ratio.