Skip to content

Commit

Permalink
feat(backmoji): allow passing canvas element as a param
Browse files Browse the repository at this point in the history
  • Loading branch information
Bernankez committed Mar 29, 2024
1 parent d94c9ef commit f12c3fe
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from "./utils/shared";
export * from "./utils/math";

export interface BackmojiOptions {
canvas?: HTMLCanvasElement;
width?: number;
height?: number;
degree?: number;
Expand All @@ -32,9 +33,8 @@ export interface RendererContext {
export type Renderer = (context: RendererContext) => void;

export function backmoji(renderer: Renderer, options?: BackmojiOptions) {
const { width = 300, height = 150, degree = 0, rowGap = 0, columnGap = 0 } = options || {};
const { width = 300, height = 150, degree = 0, rowGap = 0, columnGap = 0, canvas = document.createElement("canvas") } = options || {};

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d")!;
assert(ctx, "Current environment does not support 2d canvas rendering");

Expand Down
10 changes: 5 additions & 5 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { type BackmojiOptions, type CreateImageRendererOptions, type CreateTextRendererOptions, type Renderer, backmoji, createImageRenderer, createTextRenderer } from "backmoji";
import { useEffect, useMemo, useState } from "react";
import { type RefObject, useEffect, useMemo, useState } from "react";

export type BackmojiResult = ReturnType<typeof backmoji>;

export function useBackmoji(renderer: Renderer | null, options?: BackmojiOptions, deps?: any[]) {
export function useBackmoji(renderer: Renderer | null, canvas: RefObject<HTMLCanvasElement>, options?: Omit<BackmojiOptions, "canvas">, deps?: any[]) {
const [backmojiResult, setBackmojiResult] = useState<Partial<BackmojiResult>>({});

useEffect(() => {
if (!renderer) {
if (!renderer || !canvas.current) {
return;
}

setBackmojiResult(backmoji(renderer, options));
setBackmojiResult(backmoji(renderer, { ...options, canvas: canvas.current }));

return () => {
if (backmojiResult?.canvas) {
backmojiResult.canvas.remove();
}
};
}, [renderer, ...(deps || [])]);
}, [renderer, canvas, ...(deps || [])]);

return backmojiResult;
}
Expand Down

0 comments on commit f12c3fe

Please sign in to comment.