1.0.0 • Published 2 years ago
canvas-dimensions v1.0.0
canvas-dimensions
A utility that provides user and screen units for a 2D Canvas.
import getDocument from "canvas-dimensions";
const settings = {
// a standard paper size or [w, h]
dimensions: "A4",
// pixel resolution
pixelsPerInch: 300,
// a user coordinate space to work in
units: "cm",
};
const {
// Size in user space coordinates
width,
height,
// Size in display/screen coordinates
canvasWidth,
canvasHeight,
} = getDocument(settings);
// Setup your 2D canvas
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// Scale context to user coordinates
context.scale(canvasWidth / width, canvasHeight / height);
// Draw your graphics in user space coordinates
context.fillRect(0, 0, width, height);Install
Use npm to install.
npm install canvas-dimensions --saveUsage
output = getDocument(settings = {})
Gets document size information from the given input options.
Input options:
dimensionscan be a string defining a paper size preset like'A4'or'letter'(case insensitive), or an array of[ width, height ]unitsa string, the output units you would like to work in, can be'px','in','cm','mm'(default'px')pixelsPerInchused when converting physical sizes to canvas pixel sizes, defaults to72orientationan optional string, can be"landscape"or"portrait"and will flip the inputdimensionsaccordingly, mostly useful if you are specifying a paper size preset. Note, the paper size presets are all portrait by default.pixelRatioa factor to multiply the final canvas size by, default1
The settings input can also just be an [ width, height ] array, which is the same as passing { dimensions: [ width, height ], units: 'px' }.
Output:
unitsa string identifying the user coordinate space, such as'px'or'cm'widththe document width in user coordinatesheightthe document height in user coordinatespixelsPerInchthe document resolutioncanvasWidththe display/pixel width of the resulting canvascanvasHeightthe display/pixel height of the resulting canvaspixelRatiothe pixel ratio that has been applied to canvas size
import paperSizes from 'canvas-dimensions/paper-sizes.js'
The raw list of possible paper size keywords, see ./paper-sizes.
Recipes
Some more examples and recipes:
// 1280 x 1280 pixel image
doc = getDocument([1280, 1280]);
// Size canvas to browser size
doc = getDocument({
dimensions: [window.innerWidth, window.innerHeight],
pixelRatio: window.devicePixelRatio,
});
// 18 x 18 " artwork ready for print
doc = getDocument({
dimensions: [18, 18],
units: "in",
pixelsPerInch: 300,
});
// A4 landscape artwork, working in millimeters
doc = getDocument({
dimensions: "A4",
units: "mm",
orientation: "landscape",
pixelsPerInch: 300,
});License
MIT, see LICENSE.md for details.
1.0.0
2 years ago