Comparing version 1.0.7 to 1.0.8
@@ -7,3 +7,3 @@ type CanvasLimits = { | ||
type CreateCtxOptions = { | ||
resizeCallback?(ctx: CanvasRenderingContext2D): void | ||
resizeCallback?: (ctx: CanvasRenderingContext2D) => void | ||
limits?: CanvasLimits | ||
@@ -13,6 +13,9 @@ } | ||
type CreateCtx = ( | ||
parent: Element | null, | ||
options?: CreateCtxOptions, | ||
) => CanvasRenderingContext2D | ||
parent?: Element | null, | ||
) => { | ||
context: CanvasRenderingContext2D | ||
setParent: (parent: Element | null) => void | ||
} | ||
export declare const createCtx: CreateCtx |
52
index.js
/** | ||
* @type CreateCtx | ||
*/ | ||
export const createCtx = (parent, options = {}) => { | ||
export const createCtx = (options = {}, parent = null) => { | ||
const canvas = document.createElement('canvas') | ||
const ctx = canvas.getContext('2d') | ||
const context = canvas.getContext('2d') | ||
@@ -17,31 +17,37 @@ if (!options.limits) { | ||
const resize = () => { | ||
const width = parent.clientWidth | ||
const height = parent.clientHeight | ||
if (aspectRatio) { | ||
if (width / height < aspectRatio) { | ||
canvas.width = Math.min(width, options.limits.width) | ||
canvas.height = canvas.width / aspectRatio | ||
const setParent = parent => { | ||
const resize = () => { | ||
const width = parent.clientWidth | ||
const height = parent.clientHeight | ||
if (aspectRatio) { | ||
if (width / height < aspectRatio) { | ||
canvas.width = Math.min(width, options.limits.width) | ||
canvas.height = canvas.width / aspectRatio | ||
} else { | ||
canvas.height = Math.min(height, options.limits.height) | ||
canvas.width = canvas.height * aspectRatio | ||
} | ||
} else { | ||
canvas.height = Math.min(height, options.limits.height) | ||
canvas.width = canvas.height * aspectRatio | ||
canvas.width = width | ||
canvas.height = height | ||
} | ||
} else { | ||
canvas.width = width | ||
canvas.height = height | ||
if (options.resizeCallback) { | ||
options.resizeCallback(context) | ||
} | ||
} | ||
if (options.resizeCallback) { | ||
options.resizeCallback(ctx) | ||
} | ||
} | ||
addEventListener('resize', resize) | ||
addEventListener('resize', resize) | ||
requestAnimationFrame(resize) | ||
parent.appendChild(canvas) | ||
parent.appendChild(canvas) | ||
} | ||
requestAnimationFrame(resize) | ||
if (parent) { | ||
setParent(parent) | ||
} | ||
return ctx | ||
return { context, setParent } | ||
} |
{ | ||
"name": "ctx-2d", | ||
"version": "1.0.7", | ||
"version": "1.0.8", | ||
"description": "canvas context-2d helper", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -0,0 +0,0 @@ # Ctx 2D |
Sorry, the diff of this file is not supported yet
5012
58