├── .eslintrc.json ├── assets ├── logo.png ├── banner.png ├── example.jpg ├── example.svg └── signature.svg ├── postcss.config.mjs ├── components ├── Logo.tsx ├── Container.tsx ├── Paragraph.tsx ├── Icon.tsx ├── Wrap.tsx ├── AvatarPlaceholder.tsx ├── Link.tsx ├── DonateButton.tsx ├── Header.tsx ├── Saved.tsx ├── Footer.tsx ├── Modal.tsx ├── Menu.tsx ├── Example.tsx ├── Webcam.tsx ├── DownloadButton.tsx ├── Button.tsx ├── FAQs.tsx ├── ColorPicker.tsx └── Avatar.tsx ├── utilities ├── nanoid.ts ├── constants.ts ├── convert.ts ├── vision.ts ├── features.ts └── potrace.js ├── app ├── sitemap.ts ├── not-found.tsx ├── globals.css ├── layout.tsx ├── customize │ └── page.tsx └── page.tsx ├── tailwind.config.ts ├── .gitignore ├── next.config.ts ├── tsconfig.json ├── package.json ├── types └── index.ts ├── README.md ├── public └── logo.svg └── LICENSE /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["next/core-web-vitals"] 3 | } 4 | -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gregives/LineAvatars.com/HEAD/assets/logo.png -------------------------------------------------------------------------------- /assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gregives/LineAvatars.com/HEAD/assets/banner.png -------------------------------------------------------------------------------- /assets/example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gregives/LineAvatars.com/HEAD/assets/example.jpg -------------------------------------------------------------------------------- /postcss.config.mjs: -------------------------------------------------------------------------------- 1 | /** @type {import('postcss-load-config').Config} */ 2 | const config = { 3 | plugins: { 4 | tailwindcss: {}, 5 | }, 6 | }; 7 | 8 | export default config; 9 | -------------------------------------------------------------------------------- /components/Logo.tsx: -------------------------------------------------------------------------------- 1 | export function Logo() { 2 | return ( 3 | <> 4 | 5 | Line Avatars  6 | .com 7 | 8 | 9 | ); 10 | } 11 | -------------------------------------------------------------------------------- /utilities/nanoid.ts: -------------------------------------------------------------------------------- 1 | import { customAlphabet, customRandom } from "nanoid"; 2 | // @ts-ignore 3 | import seedrandom from "seedrandom"; 4 | 5 | const ALPHABET = 6 | "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 7 | 8 | export const generateId = customAlphabet(ALPHABET, 20); 9 | -------------------------------------------------------------------------------- /components/Container.tsx: -------------------------------------------------------------------------------- 1 | import { twMerge } from "tailwind-merge"; 2 | 3 | type ContainerProperties = JSX.IntrinsicElements["div"]; 4 | 5 | export function Container({ className, ...properties }: ContainerProperties) { 6 | return
; 7 | } 8 | -------------------------------------------------------------------------------- /components/Paragraph.tsx: -------------------------------------------------------------------------------- 1 | import { twMerge } from "tailwind-merge"; 2 | 3 | type ParagraphProperties = JSX.IntrinsicElements["p"]; 4 | 5 | export function Paragraph({ className, ...properties }: ParagraphProperties) { 6 | return

; 7 | } 8 | -------------------------------------------------------------------------------- /app/sitemap.ts: -------------------------------------------------------------------------------- 1 | import { MetadataRoute } from "next"; 2 | import { BASE_ORIGIN } from "@/utilities/constants"; 3 | 4 | export default async function sitemap(): Promise { 5 | return [ 6 | { 7 | url: `${BASE_ORIGIN}`, 8 | lastModified: new Date(), 9 | }, 10 | ]; 11 | } 12 | -------------------------------------------------------------------------------- /components/Icon.tsx: -------------------------------------------------------------------------------- 1 | import MaterialDesignIcon from "@mdi/react"; 2 | 3 | type IconProperties = React.ComponentProps; 4 | 5 | export function Icon(properties: IconProperties) { 6 | return ( 7 |

11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /app/not-found.tsx: -------------------------------------------------------------------------------- 1 | import { Button } from "@/components/Button"; 2 | import { Container } from "@/components/Container"; 3 | 4 | export default function NotFound() { 5 | return ( 6 | 7 |

404 page not found

8 | 11 |
12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | .flex > * { 6 | @apply min-w-0 min-h-0 flex-shrink-0; 7 | } 8 | 9 | strong { 10 | @apply font-semibold; 11 | } 12 | 13 | :focus { 14 | @apply outline-none; 15 | } 16 | 17 | :focus-visible, 18 | label:has(input.sr-only:focus) { 19 | @apply outline-dashed outline-2 outline-offset-2 outline-zinc-900; 20 | } 21 | -------------------------------------------------------------------------------- /components/AvatarPlaceholder.tsx: -------------------------------------------------------------------------------- 1 | import { twMerge } from "tailwind-merge"; 2 | 3 | type AvatarPlaceholderProperties = JSX.IntrinsicElements["div"]; 4 | 5 | export function AvatarPlaceholder({ 6 | className, 7 | ...properties 8 | }: AvatarPlaceholderProperties) { 9 | return ( 10 |
17 | ); 18 | } 19 | -------------------------------------------------------------------------------- /tailwind.config.ts: -------------------------------------------------------------------------------- 1 | import type { Config } from "tailwindcss"; 2 | import defaultTheme from "tailwindcss/defaultTheme"; 3 | 4 | export default { 5 | content: [ 6 | "./pages/**/*.{js,ts,jsx,tsx,mdx}", 7 | "./components/**/*.{js,ts,jsx,tsx,mdx}", 8 | "./app/**/*.{js,ts,jsx,tsx,mdx}", 9 | ], 10 | theme: { 11 | extend: { 12 | fontFamily: { 13 | sans: ["var(--font-sans)", ...defaultTheme.fontFamily.sans], 14 | }, 15 | }, 16 | }, 17 | } satisfies Config; 18 | -------------------------------------------------------------------------------- /components/Link.tsx: -------------------------------------------------------------------------------- 1 | import NextLink from "next/link"; 2 | import React from "react"; 3 | import { twMerge } from "tailwind-merge"; 4 | 5 | type LinkProperties = React.ComponentProps; 6 | 7 | export function Link({ className, ...properties }: LinkProperties) { 8 | return ( 9 | 16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /components/DonateButton.tsx: -------------------------------------------------------------------------------- 1 | import { mdiStar } from "@mdi/js"; 2 | import { Button } from "./Button"; 3 | import { twMerge } from "tailwind-merge"; 4 | 5 | type DonateButtonProperties = React.ComponentProps; 6 | 7 | export function DonateButton({ 8 | className, 9 | ...properties 10 | }: DonateButtonProperties) { 11 | return ( 12 | // @ts-ignore 13 | 21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.* 7 | .yarn/* 8 | !.yarn/patches 9 | !.yarn/plugins 10 | !.yarn/releases 11 | !.yarn/versions 12 | 13 | # testing 14 | /coverage 15 | 16 | # next.js 17 | /.next/ 18 | /out/ 19 | 20 | # production 21 | /build 22 | 23 | # misc 24 | .DS_Store 25 | *.pem 26 | 27 | # debug 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | 32 | # env files (can opt-in for committing if needed) 33 | .env* 34 | 35 | # vercel 36 | .vercel 37 | 38 | # typescript 39 | *.tsbuildinfo 40 | next-env.d.ts 41 | -------------------------------------------------------------------------------- /components/Header.tsx: -------------------------------------------------------------------------------- 1 | import { twMerge } from "tailwind-merge"; 2 | import { Link } from "./Link"; 3 | import { Container } from "./Container"; 4 | import { Logo } from "./Logo"; 5 | 6 | type HeaderProperties = JSX.IntrinsicElements["header"]; 7 | 8 | export function Header({ className, ...properties }: HeaderProperties) { 9 | return ( 10 |
14 | 15 | 16 | 17 | 18 | 19 |
20 | ); 21 | } 22 | -------------------------------------------------------------------------------- /next.config.ts: -------------------------------------------------------------------------------- 1 | import type { NextConfig } from "next"; 2 | import NextBundleAnalyzer from "@next/bundle-analyzer"; 3 | 4 | const nextConfig: NextConfig = { 5 | images: { 6 | remotePatterns: [ 7 | { 8 | protocol: "https", 9 | hostname: "images.unsplash.com", 10 | pathname: "/photo-*", 11 | }, 12 | { 13 | protocol: "https", 14 | hostname: "plus.unsplash.com", 15 | pathname: "/premium_photo-*", 16 | }, 17 | ], 18 | }, 19 | }; 20 | 21 | const withBundleAnalyzer = NextBundleAnalyzer({ 22 | enabled: process.env.ANALYZE === "true", 23 | }); 24 | 25 | export default withBundleAnalyzer(nextConfig); 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2017", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "noEmit": true, 9 | "esModuleInterop": true, 10 | "module": "esnext", 11 | "moduleResolution": "bundler", 12 | "resolveJsonModule": true, 13 | "isolatedModules": true, 14 | "jsx": "preserve", 15 | "incremental": true, 16 | "plugins": [ 17 | { 18 | "name": "next" 19 | } 20 | ], 21 | "paths": { 22 | "@/*": ["./*"] 23 | } 24 | }, 25 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], 26 | "exclude": ["node_modules"] 27 | } 28 | -------------------------------------------------------------------------------- /utilities/constants.ts: -------------------------------------------------------------------------------- 1 | export const PRODUCTION_HOST = "www.lineavatars.com"; 2 | export const DEVELOPMENT_HOST = "localhost:3000"; 3 | 4 | export const BASE_HOST = 5 | typeof window === "undefined" 6 | ? process.env.VERCEL_ENV === "production" 7 | ? PRODUCTION_HOST 8 | : process.env.VERCEL_BRANCH_URL 9 | ? process.env.VERCEL_BRANCH_URL 10 | : DEVELOPMENT_HOST 11 | : window.location.host; 12 | 13 | export const BASE_ORIGIN = `https://${BASE_HOST}`; 14 | 15 | export const SEGMENTS = [ 16 | "hair", 17 | "body", 18 | "face", 19 | "clothes", 20 | "accessories", 21 | ] as const; 22 | 23 | export const VIEWBOX = 48; 24 | 25 | export const CROPPED_RESOLUTION = 1024; 26 | 27 | export function capitalizeFirstLetter(string: string) { 28 | return String(string).charAt(0).toUpperCase() + String(string).slice(1); 29 | } 30 | -------------------------------------------------------------------------------- /components/Saved.tsx: -------------------------------------------------------------------------------- 1 | import { AvatarData } from "@/types"; 2 | import Link from "next/link"; 3 | import { useLocalStorage } from "usehooks-ts"; 4 | import { Avatar } from "./Avatar"; 5 | 6 | export function Saved() { 7 | const [avatars] = useLocalStorage("avatars", [], { 8 | initializeWithValue: false, 9 | }); 10 | 11 | if (avatars.length === 0) { 12 | return null; 13 | } 14 | 15 | return ( 16 |
17 |

Avatars you’ve generated

18 |
19 | {avatars.map((avatar) => ( 20 | 25 | 26 | 27 | ))} 28 |
29 |
30 | ); 31 | } 32 | -------------------------------------------------------------------------------- /components/Footer.tsx: -------------------------------------------------------------------------------- 1 | import { Container } from "./Container"; 2 | import { Paragraph } from "./Paragraph"; 3 | import { Logo } from "./Logo"; 4 | import { Link } from "./Link"; 5 | import { Wrap } from "./Wrap"; 6 | import { mdiStar } from "@mdi/js"; 7 | import { Icon } from "./Icon"; 8 | 9 | type FooterProperties = JSX.IntrinsicElements["footer"]; 10 | 11 | export function Footer(properties: FooterProperties) { 12 | return ( 13 |
14 | 15 | 16 | 17 | © {new Date().getFullYear()} 18 | 19 | 23 | 24 | Star on GitHub 25 | 26 | 27 | 28 |
29 | ); 30 | } 31 | -------------------------------------------------------------------------------- /components/Modal.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { Dialog, DialogPanel } from "@headlessui/react"; 4 | import { Container } from "./Container"; 5 | import { twMerge } from "tailwind-merge"; 6 | 7 | type ModalProperties = React.ComponentProps; 8 | 9 | export function Modal({ children, className, ...properties }: ModalProperties) { 10 | return ( 11 | 12 |
13 |
14 |
15 | 22 | {children} 23 | 24 |
25 |
26 |
27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /utilities/convert.ts: -------------------------------------------------------------------------------- 1 | type PotraceOptions = { 2 | turnpolicy?: "black" | "white" | "left" | "right" | "minority" | "majority"; 3 | turdsize?: number; 4 | optcurve?: boolean; 5 | alphamax?: number; 6 | opttolerance?: number; 7 | }; 8 | 9 | export async function convertImageToPath(url: string, size: number) { 10 | const { Potrace } = await import("@/utilities/potrace"); 11 | const potrace = Potrace(); 12 | 13 | potrace.loadImageFromUrl(url); 14 | const image = potrace.img; 15 | 16 | const options: PotraceOptions = { 17 | turdsize: image.width / 10, 18 | opttolerance: 10000000, 19 | alphamax: 4 / 3, 20 | }; 21 | 22 | potrace.setParameter(options); 23 | 24 | return new Promise((resolve) => { 25 | potrace.process(() => { 26 | const svg = potrace.getSVG(size / image.width); 27 | 28 | const template = document.createElement("template"); 29 | template.innerHTML = svg; 30 | const path = template.content.querySelector("path")?.getAttribute("d"); 31 | 32 | resolve(path ?? undefined); 33 | }); 34 | }); 35 | } 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "avatars", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint", 10 | "analyze": "ANALYZE=true next build" 11 | }, 12 | "dependencies": { 13 | "@headlessui/react": "^2.2.0", 14 | "@luncheon/simplify-svg-path": "^0.2.0", 15 | "@mdi/js": "^7.4.47", 16 | "@mdi/react": "^1.6.1", 17 | "@mediapipe/tasks-vision": "^0.10.20", 18 | "@next/bundle-analyzer": "^15.1.6", 19 | "nanoid": "^5.0.9", 20 | "next": "^15.1.6", 21 | "paper": "^0.12.18", 22 | "react": "^19.0.0", 23 | "react-dom": "^19.0.0", 24 | "react-shadow": "^20.6.0", 25 | "react-webcam": "^7.2.0", 26 | "tailwind-merge": "^3.0.1", 27 | "usehooks-ts": "^3.1.0" 28 | }, 29 | "devDependencies": { 30 | "@types/image-blob-reduce": "^4.1.4", 31 | "@types/node": "^20.17.17", 32 | "@types/react": "^18.3.18", 33 | "@types/react-dom": "^18.3.5", 34 | "eslint": "^8.57.1", 35 | "eslint-config-next": "^15.1.6", 36 | "postcss": "^8.5.1", 37 | "tailwindcss": "^3.4.17", 38 | "typescript": "^5.7.3" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /types/index.ts: -------------------------------------------------------------------------------- 1 | import { SEGMENTS } from "@/utilities/constants"; 2 | import { NormalizedLandmark } from "@mediapipe/tasks-vision"; 3 | 4 | export type Segment = (typeof SEGMENTS)[number]; 5 | 6 | export type Bounds = { 7 | minX: number; 8 | maxX: number; 9 | minY: number; 10 | maxY: number; 11 | scale: number; 12 | }; 13 | 14 | export type AvatarData = { 15 | id: string; 16 | createdAt: number; 17 | updatedAt: number; 18 | segments: Record; 19 | landmarks: NormalizedLandmark[]; 20 | bounds: Bounds; 21 | customizations?: { 22 | strokeWidth?: number; 23 | colors?: { 24 | outline?: string; 25 | background?: string; 26 | hair?: string; 27 | body?: string; 28 | face?: string; 29 | clothes?: string; 30 | accessories?: string; 31 | eyes?: string; 32 | eyebrows?: string; 33 | nose?: string; 34 | lips?: string; 35 | shadow?: string; 36 | }; 37 | }; 38 | }; 39 | 40 | export type Features = { 41 | eyes: NormalizedLandmark[]; 42 | eyebrows: NormalizedLandmark[][]; 43 | nose: NormalizedLandmark[]; 44 | noseDirection: number; 45 | lips: NormalizedLandmark[][]; 46 | shadow: NormalizedLandmark[]; 47 | }; 48 | 49 | export type Feature = keyof Features; 50 | -------------------------------------------------------------------------------- /app/layout.tsx: -------------------------------------------------------------------------------- 1 | import type { Metadata } from "next"; 2 | import { Inter } from "next/font/google"; 3 | import "./globals.css"; 4 | import { BASE_ORIGIN } from "@/utilities/constants"; 5 | import { Header } from "@/components/Header"; 6 | import { Footer } from "@/components/Footer"; 7 | 8 | const sans = Inter({ 9 | subsets: ["latin"], 10 | display: "swap", 11 | variable: "--font-sans", 12 | }); 13 | 14 | export const metadata: Metadata = { 15 | title: { 16 | template: "%s \u2013 Line Avatars", 17 | default: "Line Avatars \u2013 Generate a Notion-style line avatar", 18 | }, 19 | description: 20 | "Generate Notion-style line avatars for your social media profile photo. Take a photo and we'll use AI to generate a line avatar for you in 30 seconds, for free!", 21 | metadataBase: new URL(BASE_ORIGIN), 22 | alternates: { 23 | canonical: "./", 24 | }, 25 | }; 26 | 27 | export default function RootLayout({ 28 | children, 29 | }: { 30 | children: React.ReactNode; 31 | }) { 32 | return ( 33 | 34 | 35 | 36 | 37 | 38 |
39 |
40 |
{children}
41 |
42 |
43 | 44 | 45 | ); 46 | } 47 | -------------------------------------------------------------------------------- /components/Menu.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { 4 | Menu as HeadlessMenu, 5 | MenuItems as HeadlessMenuItems, 6 | } from "@headlessui/react"; 7 | import { twMerge } from "tailwind-merge"; 8 | 9 | export function Menu({ 10 | as = "div", 11 | className, 12 | ...properties 13 | }: React.ComponentProps) { 14 | return ( 15 | 20 | ); 21 | } 22 | 23 | export function MenuItems({ 24 | className, 25 | ...properties 26 | }: React.ComponentProps) { 27 | const anchor = 28 | typeof properties.anchor === "string" ? properties.anchor : "bottom start"; 29 | 30 | return ( 31 | 52 | ); 53 | } 54 | 55 | export { MenuButton, MenuItem } from "@headlessui/react"; 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Graphic showing a photo of a person turning into a line avatar](./assets/banner.png) 2 | 3 | # [LineAvatars.com](https://lineavatars.com) 4 | 5 | Website to generate Notion-style line avatars using Google's [MediaPipe AI models](https://ai.google.dev/edge/mediapipe/solutions/guide). The website runs entirely client-side and stores generated avatars in LocalStorage. 6 | 7 | The website is built with the following technologies: 8 | 9 | - [MediaPipe Solutions](https://ai.google.dev/edge/mediapipe/solutions/guide) 10 | - [Potrace](https://potrace.sourceforge.net/) 11 | - [Next.js](https://nextjs.org) 12 | - [Tailwind CSS](https://tailwindcss.com/) 13 | 14 | ## Getting Started 15 | 16 | Clone the repository: 17 | 18 | ```bash 19 | git clone https://github.com/gregives/lineavatars.com 20 | ``` 21 | 22 | Install the dependencies using Yarn: 23 | 24 | ```bash 25 | yarn 26 | ``` 27 | 28 | Run the development server: 29 | 30 | ```bash 31 | yarn dev 32 | ``` 33 | 34 | Open [http://localhost:3000](http://localhost:3000) in your browser to see the development server. 35 | 36 | ## Contribute 37 | 38 | I would appreciate help improving LineAvatars.com and the avatars it generates. Here is a list of some improvements I have in mind: 39 | 40 | - [ ] Add suite of images to test 41 | - [ ] Support all skin tones 42 | - [ ] Support glasses and other accessories 43 | - [ ] Support hats 44 | - [ ] Add detail to ears 45 | 46 | ## License 47 | 48 | Due to [Potrace](https://potrace.sourceforge.net/) being distributed under the GNU General Public License, LineAvatars.com must also be distributed under the GNU General Public License. See the [LICENSE](./LICENSE) file for details. 49 | -------------------------------------------------------------------------------- /components/Example.tsx: -------------------------------------------------------------------------------- 1 | import { twMerge } from "tailwind-merge"; 2 | 3 | type ExampleProperties = JSX.IntrinsicElements["div"]; 4 | 5 | export function Example({ 6 | className, 7 | children, 8 | ...properties 9 | }: ExampleProperties) { 10 | return ( 11 |
18 | {children} 19 | 26 | 27 | 28 | 29 |
30 | ); 31 | } 32 | -------------------------------------------------------------------------------- /components/Webcam.tsx: -------------------------------------------------------------------------------- 1 | import ReactWebcam from "react-webcam"; 2 | import { Modal } from "./Modal"; 3 | import { Button } from "./Button"; 4 | import { twMerge } from "tailwind-merge"; 5 | import { useEffect, useRef, useState } from "react"; 6 | 7 | type WebcamProperties = React.ComponentProps & { 8 | onCapture: (image: string) => void; 9 | }; 10 | 11 | export function Webcam({ 12 | onCapture, 13 | className, 14 | ...properties 15 | }: WebcamProperties) { 16 | const [loading, setLoading] = useState(false); 17 | const [devices, setDevices] = useState([]); 18 | const [deviceId, setDeviceId] = useState(); 19 | 20 | const webcamRef = useRef(null); 21 | 22 | useEffect(() => { 23 | (async () => { 24 | if (properties.open) { 25 | setDevices(await navigator.mediaDevices.enumerateDevices()); 26 | } else { 27 | setLoading(false); 28 | } 29 | })(); 30 | }, [properties.open]); 31 | 32 | const onClick = () => { 33 | if (webcamRef.current) { 34 | const image = webcamRef.current.getScreenshot(); 35 | 36 | if (image) { 37 | setLoading(true); 38 | onCapture(image); 39 | } 40 | } 41 | }; 42 | 43 | return ( 44 | 48 | 66 | 69 | 70 | ); 71 | } 72 | -------------------------------------------------------------------------------- /components/DownloadButton.tsx: -------------------------------------------------------------------------------- 1 | import { mdiDownload, mdiStar } from "@mdi/js"; 2 | import { Button } from "./Button"; 3 | import { Modal } from "./Modal"; 4 | import { useState } from "react"; 5 | import { Logo } from "./Logo"; 6 | import { Paragraph } from "./Paragraph"; 7 | import { Wrap } from "./Wrap"; 8 | import Image from "next/image"; 9 | import signature from "@/assets/signature.svg"; 10 | import { DonateButton } from "./DonateButton"; 11 | 12 | function download(filename: string, avatar: string) { 13 | const element = document.createElement("a"); 14 | element.setAttribute( 15 | "href", 16 | "data:image/svg+xml;charset=utf-8," + encodeURIComponent(avatar) 17 | ); 18 | element.setAttribute("download", filename); 19 | 20 | element.style.display = "none"; 21 | document.body.appendChild(element); 22 | element.click(); 23 | document.body.removeChild(element); 24 | } 25 | 26 | type DownloadButtonProperties = React.ComponentProps; 27 | 28 | export function DownloadButton(properties: DownloadButtonProperties) { 29 | const [open, setOpen] = useState(false); 30 | 31 | const downloadAvatar = () => { 32 | const avatar = document.getElementById("download"); 33 | 34 | if (avatar) { 35 | const shadowRoot = avatar.shadowRoot; 36 | 37 | if (shadowRoot) { 38 | download( 39 | "avatar-" + 40 | new Date().toISOString().split(/\D/).slice(0, 6).join("") + 41 | ".svg", 42 | shadowRoot.innerHTML 43 | ); 44 | } 45 | } 46 | 47 | setOpen(true); 48 | }; 49 | 50 | return ( 51 | <> 52 | 59 | 60 |

We hope you like your avatar

61 | 62 | If you want to show your appreciation for your new avatar, please 63 | consider donating. Just $1 will help us to make even better. 64 | 65 | Greg Ives 70 | 71 | Creator of 72 | 73 | 74 | 75 | 78 | 79 |
80 | 81 | ); 82 | } 83 | -------------------------------------------------------------------------------- /components/Button.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { twMerge } from "tailwind-merge"; 4 | import NextLink from "next/link"; 5 | import React from "react"; 6 | import { Icon } from "./Icon"; 7 | import { mdiLoading } from "@mdi/js"; 8 | 9 | type ButtonProperties = ( 10 | | ({ 11 | href?: undefined; 12 | } & JSX.IntrinsicElements["button"]) 13 | | Omit, "as"> 14 | ) & { 15 | size?: "xs" | "sm" | "md" | "lg" | "xl"; 16 | color?: "zinc" | "teal"; 17 | variant?: "fill" | "soft" | "outline" | "menu" | "text"; 18 | disabled?: boolean; 19 | loading?: boolean; 20 | leadingIcon?: string; 21 | trailingIcon?: string; 22 | as?: React.ElementType; 23 | }; 24 | 25 | const styles = { 26 | fill: { 27 | teal: "bg-teal-600 hover:bg-teal-500 text-white", 28 | zinc: "bg-zinc-700 hover:bg-zinc-500 text-white", 29 | }, 30 | soft: { 31 | teal: "bg-teal-200 hover:bg-teal-300", 32 | zinc: "bg-zinc-100 hover:bg-zinc-200", 33 | }, 34 | outline: { 35 | teal: "ring-2 ring-inset ring-teal-200 hover:ring-teal-400", 36 | zinc: "ring-2 ring-inset ring-zinc-200 hover:ring-zinc-400", 37 | }, 38 | menu: { 39 | teal: "hover:bg-teal-100 ui-active:bg-teal-100", 40 | zinc: "hover:bg-zinc-100 ui-active:bg-zinc-100", 41 | }, 42 | text: { 43 | teal: "hover:bg-teal-100 text-teal-700", 44 | zinc: "hover:bg-zinc-100", 45 | }, 46 | }; 47 | 48 | export function Button({ 49 | children, 50 | className, 51 | href, 52 | size = "md", 53 | color = "teal", 54 | variant = "soft", 55 | disabled, 56 | loading, 57 | leadingIcon, 58 | trailingIcon, 59 | as: Component = href === undefined ? "button" : NextLink, 60 | ...properties 61 | }: ButtonProperties) { 62 | className = twMerge( 63 | "flex justify-center items-center font-medium rounded-xl", 64 | size === "xs" 65 | ? "py-1 px-2 space-x-0.5 text-xs" 66 | : size === "sm" 67 | ? "py-1.5 px-3 space-x-1 text-sm" 68 | : size === "md" 69 | ? "py-2 px-4 space-x-1.5 text-base" 70 | : size === "lg" 71 | ? "py-2.5 px-5 space-x-2 text-base sm:text-lg" 72 | : "py-2.5 px-5 space-x-2 sm:py-3 sm:px-6 sm:space-x-2.5 text-lg sm:text-xl", 73 | variant === "menu" && "rounded-none", 74 | styles[variant][color], 75 | className 76 | ); 77 | 78 | return ( 79 | 85 | {!trailingIcon && loading ? ( 86 | 87 | ) : leadingIcon ? ( 88 | 89 | ) : null} 90 | {children && {children}} 91 | {trailingIcon && loading ? ( 92 | 93 | ) : trailingIcon ? ( 94 | 95 | ) : null} 96 | 97 | ); 98 | } 99 | -------------------------------------------------------------------------------- /components/FAQs.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Disclosure, 3 | DisclosureButton, 4 | DisclosurePanel, 5 | } from "@headlessui/react"; 6 | import { twMerge } from "tailwind-merge"; 7 | import { Icon } from "./Icon"; 8 | import { mdiChevronDown, mdiStar } from "@mdi/js"; 9 | import { Link } from "./Link"; 10 | import { Logo } from "./Logo"; 11 | import { Button } from "./Button"; 12 | import { DonateButton } from "./DonateButton"; 13 | 14 | const questions = [ 15 | { 16 | question: "What is a line avatar?", 17 | answer: ( 18 | <> 19 | A line avatar, or a Notion-style line avatar, is a simple representation 20 | of a person’s face. It is most often used as a profile photo for 21 | social media. 22 | 23 | ), 24 | }, 25 | { 26 | question: "Who first created line avatars?", 27 | answer: ( 28 | <> 29 | Line avatars were popularised by Notion, a productivity app. Notion have 30 | since created{" "} 31 | 35 | Notion Faces 36 | {" "} 37 | where you can create your own (although it doesn’t use your webcam 38 | like we do). 39 | 40 | ), 41 | }, 42 | { 43 | question: "How much do line avatars cost?", 44 | answer: ( 45 | <> 46 | Line avatars can cost as much as $150 when they are created for you by a 47 | designer, however, by using AI we can create you one for free! 48 | 49 | ), 50 | }, 51 | { 52 | question: ( 53 | <> 54 | Is safe to use? 55 | 56 | ), 57 | answer: ( 58 | <> 59 | Yes, the processing is done entirely in your browser and you can view 60 | the source code on{" "} 61 | 65 | GitHub 66 | 67 | . 68 | 69 | ), 70 | }, 71 | { 72 | question: ( 73 | <> 74 | How can I support ? 75 | 76 | ), 77 | answer: ( 78 | <> 79 | If you know how to code, you can help to improve by 80 | contributing to our{" "} 81 | 85 | GitHub repository 86 | 87 | . If you don’t know how to code, any donation would be greatly 88 | appreciated. 89 |
90 | 91 |
92 | 93 | ), 94 | }, 95 | ]; 96 | 97 | type FAQsProperties = JSX.IntrinsicElements["div"]; 98 | 99 | export function FAQs({ className, ...properties }: FAQsProperties) { 100 | return ( 101 |
102 | {questions.map(({ question, answer }, index) => ( 103 | 104 |

105 | 106 | {question} 107 | 108 |   109 | 113 | 114 | 115 |

116 | {answer} 117 |
118 | ))} 119 |
120 | ); 121 | } 122 | -------------------------------------------------------------------------------- /app/customize/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { Avatar } from "@/components/Avatar"; 4 | import { AvatarPlaceholder } from "@/components/AvatarPlaceholder"; 5 | import { Button } from "@/components/Button"; 6 | import { ColorPicker } from "@/components/ColorPicker"; 7 | import { Container } from "@/components/Container"; 8 | import { DownloadButton } from "@/components/DownloadButton"; 9 | import { Paragraph } from "@/components/Paragraph"; 10 | import { Saved } from "@/components/Saved"; 11 | import { Wrap } from "@/components/Wrap"; 12 | import { AvatarData } from "@/types"; 13 | import { capitalizeFirstLetter } from "@/utilities/constants"; 14 | import { mdiAutorenew } from "@mdi/js"; 15 | import { useSearchParams } from "next/navigation"; 16 | import { Suspense } from "react"; 17 | import { useLocalStorage } from "usehooks-ts"; 18 | 19 | const CUSTOMIZABLE_FEATURES = [ 20 | "outline", 21 | "background", 22 | "hair", 23 | "body", 24 | "face", 25 | "clothes", 26 | "accessories", 27 | "eyes", 28 | "eyebrows", 29 | "nose", 30 | "lips", 31 | "shadow", 32 | ] as const; 33 | 34 | type CustomizableFeature = (typeof CUSTOMIZABLE_FEATURES)[number]; 35 | 36 | function CustomizeAvatar() { 37 | const [avatars, setAvatars] = useLocalStorage("avatars", [], { 38 | initializeWithValue: false, 39 | }); 40 | 41 | const searchParams = useSearchParams(); 42 | 43 | const avatarId = searchParams.get("avatar"); 44 | const avatar = avatars.find((avatar) => avatar.id === avatarId); 45 | 46 | const updateColor = (feature: CustomizableFeature, color: string) => { 47 | const avatarIndex = avatars.findIndex((avatar) => avatar.id === avatarId); 48 | 49 | avatars[avatarIndex].customizations = { 50 | ...avatars[avatarIndex].customizations, 51 | colors: { 52 | ...avatars[avatarIndex].customizations?.colors, 53 | [feature]: color, 54 | }, 55 | }; 56 | 57 | setAvatars([...avatars]); 58 | }; 59 | 60 | const resetColor = (feature: CustomizableFeature) => { 61 | const avatarIndex = avatars.findIndex((avatar) => avatar.id === avatarId); 62 | 63 | delete avatars[avatarIndex].customizations?.colors?.[feature]; 64 | 65 | setAvatars([...avatars]); 66 | }; 67 | 68 | return ( 69 | <> 70 |
71 | {avatar ? ( 72 | 73 | ) : ( 74 | 75 | )} 76 |
77 |
78 | {CUSTOMIZABLE_FEATURES.map((feature) => ( 79 |
80 |

{capitalizeFirstLetter(feature)}

81 | 84 | updateColor(feature, color)} 88 | /> 89 |
90 | ))} 91 |
92 | 93 | ); 94 | } 95 | 96 | export default function CustomizePage() { 97 | return ( 98 | 99 |

Customize your avatar

100 | 103 |
104 | 105 |
106 | Loading… 107 | 108 | } 109 | > 110 | 111 |
112 | 113 | 114 | 117 | 118 | 119 |
120 | ); 121 | } 122 | -------------------------------------------------------------------------------- /utilities/vision.ts: -------------------------------------------------------------------------------- 1 | import type { NormalizedLandmark } from "@mediapipe/tasks-vision"; 2 | import { SEGMENTS, VIEWBOX } from "./constants"; 3 | import { Bounds, AvatarData, Segment } from "@/types"; 4 | import { convertImageToPath } from "./convert"; 5 | import { generateId } from "./nanoid"; 6 | 7 | function createCanvas(width: number, height: number) { 8 | const canvas = document.createElement("canvas"); 9 | canvas.width = width; 10 | canvas.height = height; 11 | 12 | const context = canvas.getContext("2d"); 13 | 14 | if (context === null) { 15 | throw new Error("Could not get canvas context"); 16 | } 17 | 18 | return { 19 | canvas, 20 | context, 21 | }; 22 | } 23 | 24 | function getBounds(landmarks: NormalizedLandmark[]): Bounds { 25 | const minX = Math.min(...landmarks.map((landmark) => landmark.x)); 26 | const maxX = Math.max(...landmarks.map((landmark) => landmark.x)); 27 | const minY = Math.min(...landmarks.map((landmark) => landmark.y)); 28 | const maxY = Math.max(...landmarks.map((landmark) => landmark.y)); 29 | 30 | return { 31 | minX, 32 | maxX, 33 | minY, 34 | maxY, 35 | scale: Math.max(0.5 / (maxY - minY), 1), 36 | }; 37 | } 38 | 39 | export async function getFaceData(photo: string): Promise { 40 | const image = document.createElement("img"); 41 | 42 | await new Promise((resolve) => { 43 | image.onload = resolve; 44 | image.src = photo; 45 | }); 46 | 47 | const { FaceLandmarker, FilesetResolver, ImageSegmenter } = await import( 48 | "@mediapipe/tasks-vision" 49 | ); 50 | 51 | const vision = await FilesetResolver.forVisionTasks( 52 | "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm" 53 | ); 54 | 55 | const [imageSegmenter, faceLandmarker] = await Promise.all([ 56 | ImageSegmenter.createFromOptions(vision, { 57 | baseOptions: { 58 | modelAssetPath: 59 | "https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/latest/selfie_multiclass_256x256.tflite", 60 | }, 61 | outputCategoryMask: true, 62 | outputConfidenceMasks: false, 63 | runningMode: "IMAGE", 64 | }), 65 | FaceLandmarker.createFromOptions(vision, { 66 | baseOptions: { 67 | modelAssetPath: 68 | "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task", 69 | }, 70 | runningMode: "IMAGE", 71 | numFaces: 1, 72 | }), 73 | ]); 74 | 75 | const faceLandmarkerResult = faceLandmarker.detect(image); 76 | 77 | const landmarks = faceLandmarkerResult.faceLandmarks[0]; 78 | const bounds = getBounds(landmarks); 79 | 80 | const imageSegmenterResult = imageSegmenter.segment(image); 81 | 82 | if (imageSegmenterResult.categoryMask === undefined) { 83 | throw new Error("Could not segment image"); 84 | } 85 | 86 | const mask = imageSegmenterResult.categoryMask.getAsUint8Array(); 87 | 88 | // @ts-ignore 89 | const segments: Record = {}; 90 | 91 | await Promise.all( 92 | SEGMENTS.map(async (segment, segmentIndex) => { 93 | const { canvas, context } = createCanvas(image.width, image.height); 94 | 95 | const imageData = context.getImageData( 96 | 0, 97 | 0, 98 | image.width, 99 | image.height 100 | ).data; 101 | 102 | mask.forEach((value, index) => { 103 | if (value === segmentIndex + 1) { 104 | imageData[index * 4] = 0; 105 | imageData[index * 4 + 1] = 0; 106 | imageData[index * 4 + 2] = 0; 107 | imageData[index * 4 + 3] = 255; 108 | } else { 109 | imageData[index * 4] = 255; 110 | imageData[index * 4 + 1] = 255; 111 | imageData[index * 4 + 2] = 255; 112 | imageData[index * 4 + 3] = 255; 113 | } 114 | }); 115 | 116 | const uint8Array = new Uint8ClampedArray(imageData.buffer); 117 | const dataNew = new ImageData(uint8Array, image.width, image.height); 118 | context.putImageData(dataNew, 0, 0); 119 | 120 | segments[segment] = await convertImageToPath( 121 | canvas.toDataURL(), 122 | bounds.scale * VIEWBOX 123 | ); 124 | }) 125 | ); 126 | 127 | const createdAt = Date.now(); 128 | 129 | return { 130 | id: generateId(), 131 | createdAt, 132 | updatedAt: createdAt, 133 | segments, 134 | landmarks, 135 | bounds, 136 | }; 137 | } 138 | -------------------------------------------------------------------------------- /components/ColorPicker.tsx: -------------------------------------------------------------------------------- 1 | import { twMerge } from "tailwind-merge"; 2 | import { Button } from "./Button"; 3 | import { Modal } from "./Modal"; 4 | import { useState } from "react"; 5 | import colors from "tailwindcss/colors"; 6 | import { mdiWaterOff } from "@mdi/js"; 7 | import { capitalizeFirstLetter } from "@/utilities/constants"; 8 | 9 | type ColorPickerProperties = Omit< 10 | React.ComponentProps, 11 | "color" | "onChange" 12 | > & { 13 | color: string | undefined; 14 | onChange: (color: string) => void; 15 | }; 16 | 17 | export function ColorPicker({ 18 | color = "#000", 19 | onChange, 20 | className, 21 | ...properties 22 | }: ColorPickerProperties) { 23 | const [open, setOpen] = useState(false); 24 | 25 | return ( 26 | <> 27 | {/* @ts-ignore */} 28 | 41 | 42 |

Pick a color

43 |
44 |
45 | 57 | 68 | 78 |
79 |
80 |
81 | {( 82 | [ 83 | "zinc", 84 | "red", 85 | "orange", 86 | "amber", 87 | "yellow", 88 | "lime", 89 | "green", 90 | "emerald", 91 | "teal", 92 | "cyan", 93 | "sky", 94 | "blue", 95 | "indigo", 96 | "violet", 97 | "purple", 98 | "fuchsia", 99 | "pink", 100 | "rose", 101 | ] as const 102 | ).flatMap((hue, hueIndex, hues) => 103 | ( 104 | [ 105 | "50", 106 | "100", 107 | "200", 108 | "300", 109 | "400", 110 | "500", 111 | "600", 112 | "700", 113 | "800", 114 | "900", 115 | "950", 116 | ] as const 117 | ).map((shade, shadeIndex, shades) => ( 118 | 147 | )) 148 | )} 149 |
150 |
151 | 152 | ); 153 | } 154 | -------------------------------------------------------------------------------- /utilities/features.ts: -------------------------------------------------------------------------------- 1 | import { AvatarData, Features } from "@/types"; 2 | import { NormalizedLandmark } from "@mediapipe/tasks-vision"; 3 | 4 | function averageLandmark( 5 | landmark1: NormalizedLandmark, 6 | landmark2: NormalizedLandmark, 7 | weight = 0.5 8 | ): NormalizedLandmark { 9 | return { 10 | x: landmark1.x + (landmark2.x - landmark1.x) * weight, 11 | y: landmark1.y + (landmark2.y - landmark1.y) * weight, 12 | z: landmark1.z + (landmark2.z - landmark1.z) * weight, 13 | visibility: 1, 14 | }; 15 | } 16 | 17 | export function buildFeatures(avatar: AvatarData): Features { 18 | const middleOfNose = avatar.landmarks[5]; 19 | const leftEye = avatar.landmarks[468]; 20 | const rightEye = avatar.landmarks[473]; 21 | 22 | const eyes: NormalizedLandmark[] = []; 23 | 24 | if (leftEye.x < middleOfNose.x) { 25 | eyes.push(leftEye); 26 | } 27 | 28 | if (rightEye.x > middleOfNose.x) { 29 | eyes.push(rightEye); 30 | } 31 | 32 | const leftEyebrow = [ 33 | averageLandmark(avatar.landmarks[65], avatar.landmarks[55], 2 / 3), 34 | avatar.landmarks[65], 35 | avatar.landmarks[52], 36 | avatar.landmarks[53], 37 | averageLandmark(avatar.landmarks[46], avatar.landmarks[225]), 38 | ].filter((point, index, points) => 39 | index ? point.x < points[index - 1].x : true 40 | ); 41 | 42 | const rightEyebrow: NormalizedLandmark[] = [ 43 | averageLandmark(avatar.landmarks[295], avatar.landmarks[285], 2 / 3), 44 | avatar.landmarks[295], 45 | avatar.landmarks[282], 46 | avatar.landmarks[283], 47 | averageLandmark(avatar.landmarks[276], avatar.landmarks[445]), 48 | ].filter((point, index, points) => 49 | index ? point.x > points[index - 1].x : true 50 | ); 51 | 52 | const leftNostril = avatar.landmarks[60]; 53 | const endOfNose = avatar.landmarks[4]; 54 | const rightNostril = avatar.landmarks[290]; 55 | 56 | let nose: NormalizedLandmark[]; 57 | let noseDirection: number; 58 | 59 | if ( 60 | Math.abs(endOfNose.x - leftNostril.x) > 61 | Math.abs(endOfNose.x - rightNostril.x) 62 | ) { 63 | noseDirection = 1; 64 | nose = [ 65 | avatar.landmarks[168], 66 | avatar.landmarks[6], 67 | avatar.landmarks[197], 68 | avatar.landmarks[195], 69 | avatar.landmarks[5], 70 | avatar.landmarks[4], 71 | avatar.landmarks[1], 72 | avatar.landmarks[19], 73 | avatar.landmarks[94], 74 | avatar.landmarks[99], 75 | avatar.landmarks[240], 76 | ]; 77 | } else { 78 | noseDirection = -1; 79 | nose = [ 80 | avatar.landmarks[168], 81 | avatar.landmarks[6], 82 | avatar.landmarks[197], 83 | avatar.landmarks[195], 84 | avatar.landmarks[5], 85 | avatar.landmarks[4], 86 | avatar.landmarks[1], 87 | avatar.landmarks[19], 88 | avatar.landmarks[94], 89 | avatar.landmarks[328], 90 | avatar.landmarks[460], 91 | ]; 92 | } 93 | 94 | const leftTopLip: NormalizedLandmark[] = [ 95 | avatar.landmarks[0], 96 | avatar.landmarks[37], 97 | avatar.landmarks[39], 98 | avatar.landmarks[40], 99 | avatar.landmarks[185], 100 | avatar.landmarks[61], 101 | avatar.landmarks[78], 102 | avatar.landmarks[191], 103 | avatar.landmarks[80], 104 | avatar.landmarks[81], 105 | avatar.landmarks[82], 106 | avatar.landmarks[13], 107 | ]; 108 | 109 | const rightTopLip: NormalizedLandmark[] = [ 110 | avatar.landmarks[0], 111 | avatar.landmarks[267], 112 | avatar.landmarks[269], 113 | avatar.landmarks[270], 114 | avatar.landmarks[409], 115 | avatar.landmarks[291], 116 | avatar.landmarks[308], 117 | avatar.landmarks[415], 118 | avatar.landmarks[310], 119 | avatar.landmarks[311], 120 | avatar.landmarks[312], 121 | avatar.landmarks[13], 122 | ]; 123 | 124 | const leftBottomLip: NormalizedLandmark[] = [ 125 | avatar.landmarks[17], 126 | avatar.landmarks[84], 127 | avatar.landmarks[181], 128 | avatar.landmarks[91], 129 | avatar.landmarks[146], 130 | avatar.landmarks[61], 131 | avatar.landmarks[78], 132 | avatar.landmarks[95], 133 | avatar.landmarks[88], 134 | avatar.landmarks[178], 135 | avatar.landmarks[87], 136 | avatar.landmarks[14], 137 | ]; 138 | 139 | const rightBottomLip: NormalizedLandmark[] = [ 140 | avatar.landmarks[17], 141 | avatar.landmarks[314], 142 | avatar.landmarks[405], 143 | avatar.landmarks[321], 144 | avatar.landmarks[375], 145 | avatar.landmarks[291], 146 | avatar.landmarks[308], 147 | avatar.landmarks[324], 148 | avatar.landmarks[318], 149 | avatar.landmarks[402], 150 | avatar.landmarks[317], 151 | avatar.landmarks[14], 152 | ]; 153 | 154 | return { 155 | eyes, 156 | eyebrows: [leftEyebrow, rightEyebrow], 157 | nose, 158 | noseDirection, 159 | lips: [ 160 | [...leftTopLip.reverse(), ...rightTopLip.slice(1, -1)], 161 | [...rightBottomLip.reverse(), ...leftBottomLip.slice(1, -1)], 162 | ], 163 | shadow: [ 164 | avatar.landmarks[93], 165 | avatar.landmarks[58], 166 | averageLandmark(avatar.landmarks[18], avatar.landmarks[152], 2.5), 167 | avatar.landmarks[288], 168 | avatar.landmarks[323], 169 | ], 170 | }; 171 | } 172 | -------------------------------------------------------------------------------- /components/Avatar.tsx: -------------------------------------------------------------------------------- 1 | import root from "react-shadow"; 2 | import { AvatarData } from "@/types"; 3 | import { VIEWBOX } from "@/utilities/constants"; 4 | import { buildFeatures } from "@/utilities/features"; 5 | import simplifySvgPath from "@luncheon/simplify-svg-path"; 6 | import { NormalizedLandmark } from "@mediapipe/tasks-vision"; 7 | import { twMerge } from "tailwind-merge"; 8 | 9 | type AvatarProperties = JSX.IntrinsicElements["div"] & { 10 | avatar: AvatarData; 11 | }; 12 | 13 | export function Avatar({ avatar, className, ...properties }: AvatarProperties) { 14 | const translateX = Math.min( 15 | Math.max( 16 | (0.5 - 17 | ((avatar.bounds.minX + avatar.bounds.maxX) / 2) * avatar.bounds.scale) * 18 | VIEWBOX, 19 | VIEWBOX - VIEWBOX * avatar.bounds.scale 20 | ), 21 | 0 22 | ); 23 | 24 | const translateY = Math.min( 25 | Math.max( 26 | (0.5 - 27 | ((avatar.bounds.minY + avatar.bounds.maxY) / 2) * avatar.bounds.scale) * 28 | VIEWBOX, 29 | VIEWBOX - VIEWBOX * avatar.bounds.scale 30 | ), 31 | 0 32 | ); 33 | 34 | const transform = `translate(${translateX} ${translateY})`; 35 | 36 | const pointToViewbox = ( 37 | point: NormalizedLandmark, 38 | offset = { 39 | x: 0, 40 | y: 0, 41 | } 42 | ) => { 43 | return [ 44 | point.x * VIEWBOX * avatar.bounds.scale + translateX + offset.x, 45 | point.y * VIEWBOX * avatar.bounds.scale + translateY + offset.y, 46 | ] as const; 47 | }; 48 | 49 | const features = buildFeatures(avatar); 50 | 51 | const strokeColor = avatar.customizations?.colors?.outline ?? "#000"; 52 | const strokeWidth = avatar.customizations?.strokeWidth ?? 1; 53 | 54 | return ( 55 | 62 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 83 | 87 | {features.shadow && ( 88 | pointToViewbox(point)) 91 | )} 92 | fill={avatar.customizations?.colors?.shadow ?? "#0003"} 93 | clipPath="url(#bodyClip)" 94 | /> 95 | )} 96 | 103 | 109 | 113 | {features.eyes.map((eye, index) => { 114 | const [cx, cy] = pointToViewbox(eye); 115 | 116 | return ( 117 | 126 | ); 127 | })} 128 | {features.eyebrows.map((eyebrow, index) => ( 129 | pointToViewbox(point)))} 132 | fill="none" 133 | stroke={avatar.customizations?.colors?.eyebrows ?? strokeColor} 134 | strokeWidth={strokeWidth} 135 | clipPath="url(#faceClip)" 136 | /> 137 | ))} 138 | {features.nose && ( 139 | 142 | pointToViewbox(point, { 143 | x: features.noseDirection, 144 | y: 0, 145 | }) 146 | ), 147 | { 148 | precision: 2, 149 | tolerance: 1, 150 | } 151 | )} 152 | fill={avatar.customizations?.colors?.face ?? "#fff"} 153 | stroke={avatar.customizations?.colors?.nose ?? strokeColor} 154 | strokeWidth={strokeWidth} 155 | clipPath="url(#faceClip)" 156 | /> 157 | )} 158 | {features.lips.map((lip, index) => ( 159 | pointToViewbox(point)), 163 | { 164 | tolerance: 0, 165 | precision: 10, 166 | closed: true, 167 | } 168 | )} 169 | fill={avatar.customizations?.colors?.lips ?? "#e4e4e7"} 170 | stroke={avatar.customizations?.colors?.lips ?? "#e4e4e7"} 171 | strokeWidth={strokeWidth * 0.25} 172 | clipPath="url(#faceClip)" 173 | /> 174 | ))} 175 | 181 | {avatar.segments.hair && ( 182 | 189 | )} 190 | {avatar.segments.accessories && ( 191 | 198 | )} 199 | 200 | 201 | ); 202 | } 203 | -------------------------------------------------------------------------------- /app/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { Button } from "@/components/Button"; 4 | import { Container } from "@/components/Container"; 5 | import { Paragraph } from "@/components/Paragraph"; 6 | import { Webcam } from "@/components/Webcam"; 7 | import { mdiAutorenew, mdiCamera, mdiPalette, mdiUpload } from "@mdi/js"; 8 | import { ChangeEventHandler, useRef, useState } from "react"; 9 | import { CROPPED_RESOLUTION } from "@/utilities/constants"; 10 | import Image from "next/image"; 11 | import exampleJPG from "@/assets/example.jpg"; 12 | import exampleSVG from "@/assets/example.svg"; 13 | import { Avatar } from "@/components/Avatar"; 14 | import { Example } from "@/components/Example"; 15 | import { AvatarData } from "@/types"; 16 | import { getFaceData } from "@/utilities/vision"; 17 | import { useLocalStorage } from "usehooks-ts"; 18 | import { Wrap } from "@/components/Wrap"; 19 | import { Saved } from "@/components/Saved"; 20 | import { AvatarPlaceholder } from "@/components/AvatarPlaceholder"; 21 | import { DownloadButton } from "@/components/DownloadButton"; 22 | import { FAQs } from "@/components/FAQs"; 23 | 24 | const fileToBase64 = (file: Blob): Promise => 25 | new Promise((resolve, reject) => { 26 | const reader = new FileReader(); 27 | reader.readAsDataURL(file); 28 | reader.onload = () => resolve(reader.result as string); 29 | reader.onerror = reject; 30 | }); 31 | 32 | export default function HomePage() { 33 | const uploadRef = useRef(null); 34 | 35 | const [uploading, setUploading] = useState(false); 36 | const [webcamOpen, setWebcamOpen] = useState(false); 37 | 38 | const [photo, setPhoto] = useState(); 39 | const [avatar, setAvatar] = useState(); 40 | 41 | const [, setValue] = useLocalStorage("avatars", [], { 42 | initializeWithValue: false, 43 | }); 44 | 45 | const generateAvatar = async (image: string) => { 46 | setWebcamOpen(false); 47 | 48 | const canvas = document.createElement("canvas"); 49 | canvas.width = CROPPED_RESOLUTION; 50 | canvas.height = CROPPED_RESOLUTION; 51 | 52 | const context = canvas.getContext("2d"); 53 | 54 | if (context === null) { 55 | return; 56 | } 57 | 58 | const imageObject = new window.Image(); 59 | 60 | imageObject.onload = async () => { 61 | const sourceSize = Math.min(imageObject.width, imageObject.height); 62 | 63 | context.drawImage( 64 | imageObject, 65 | imageObject.width / 2 - sourceSize / 2, 66 | imageObject.height / 2 - sourceSize / 2, 67 | sourceSize, 68 | sourceSize, 69 | 0, 70 | 0, 71 | CROPPED_RESOLUTION, 72 | CROPPED_RESOLUTION 73 | ); 74 | 75 | const photo = canvas.toDataURL("image/jpeg", 0.75); 76 | 77 | setPhoto(photo); 78 | const avatar = await getFaceData(photo); 79 | setAvatar(avatar); 80 | setValue((avatars) => [avatar, ...avatars]); 81 | }; 82 | 83 | imageObject.src = image; 84 | }; 85 | 86 | const onChange: ChangeEventHandler = async (event) => { 87 | const files = event.target.files; 88 | 89 | if (files && files.length > 0) { 90 | const [file] = files; 91 | 92 | setUploading(true); 93 | 94 | const imageBase64 = await fileToBase64(file); 95 | 96 | generateAvatar(imageBase64); 97 | setUploading(false); 98 | } 99 | }; 100 | 101 | return ( 102 | 103 | {photo ? ( 104 | <> 105 |

Generating your avatar…

106 | 107 | 115 | {avatar ? ( 116 | 117 | ) : ( 118 | 119 | )} 120 | 121 | {avatar && ( 122 | <> 123 | 124 | Here’s your avatar! Download an SVG of your avatar or 125 | click customize to change the colors. 126 | 127 | 128 | 129 | 137 | 147 | 148 | 149 | )} 150 | 151 | ) : ( 152 | <> 153 |

154 | Generate your line avatar in 30 seconds 155 |

156 | 157 | Photo from webcam 163 | Photo from webcam 169 | 170 | 171 | Upload or capture a photo of your face, preferably at a slight 172 | angle. Then we’ll use AI to generate a line avatar for you.{" "} 173 | For free! 174 | 175 | 176 | 185 | 201 | 202 | 203 | 204 | )} 205 | 206 | { 209 | setWebcamOpen(false); 210 | }} 211 | onCapture={generateAvatar} 212 | /> 213 |
214 | ); 215 | } 216 | -------------------------------------------------------------------------------- /assets/example.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 20 | 21 | 25 | 26 | 28 | 30 | 32 | 34 | 36 | 39 | 42 | 43 | 47 | 49 | -------------------------------------------------------------------------------- /public/logo.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 32 | 33 | 35 | 37 | 39 | 41 | 43 | 46 | 49 | 50 | 54 | 56 | 57 | -------------------------------------------------------------------------------- /assets/signature.svg: -------------------------------------------------------------------------------- 1 | 3 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /utilities/potrace.js: -------------------------------------------------------------------------------- 1 | // prettier-ignore 2 | 3 | // https://github.com/kilobtye/potrace 4 | export const Potrace = function() { 5 | 6 | function Point(x, y) { 7 | this.x = x; 8 | this.y = y; 9 | } 10 | 11 | Point.prototype.copy = function(){ 12 | return new Point(this.x, this.y); 13 | }; 14 | 15 | function Bitmap(w, h) { 16 | this.w = w; 17 | this.h = h; 18 | this.size = w * h; 19 | this.arraybuffer = new ArrayBuffer(this.size); 20 | this.data = new Int8Array(this.arraybuffer); 21 | } 22 | 23 | Bitmap.prototype.at = function (x, y) { 24 | return (x >= 0 && x < this.w && y >=0 && y < this.h) && 25 | this.data[this.w * y + x] === 1; 26 | }; 27 | 28 | Bitmap.prototype.index = function(i) { 29 | var point = new Point(); 30 | point.y = Math.floor(i / this.w); 31 | point.x = i - point.y * this.w; 32 | return point; 33 | }; 34 | 35 | Bitmap.prototype.flip = function(x, y) { 36 | if (this.at(x, y)) { 37 | this.data[this.w * y + x] = 0; 38 | } else { 39 | this.data[this.w * y + x] = 1; 40 | } 41 | }; 42 | 43 | Bitmap.prototype.copy = function() { 44 | var bm = new Bitmap(this.w, this.h), i; 45 | for (i = 0; i < this.size; i++) { 46 | bm.data[i] = this.data[i]; 47 | } 48 | return bm; 49 | }; 50 | 51 | function Path() { 52 | this.area = 0; 53 | this.len = 0; 54 | this.curve = {}; 55 | this.pt = []; 56 | this.minX = 100000; 57 | this.minY = 100000; 58 | this.maxX= -1; 59 | this.maxY = -1; 60 | } 61 | 62 | function Curve(n) { 63 | this.n = n; 64 | this.tag = new Array(n); 65 | this.c = new Array(n * 3); 66 | this.alphaCurve = 0; 67 | this.vertex = new Array(n); 68 | this.alpha = new Array(n); 69 | this.alpha0 = new Array(n); 70 | this.beta = new Array(n); 71 | } 72 | 73 | var imgElement = document.createElement("img"), 74 | imgCanvas = document.createElement("canvas"), 75 | bm = null, 76 | pathlist = [], 77 | callback, 78 | info = { 79 | isReady: false, 80 | turnpolicy: "minority", 81 | turdsize: 2, 82 | optcurve: true, 83 | alphamax: 1, 84 | opttolerance: 0.2 85 | }; 86 | 87 | imgElement.onload = function() { 88 | loadCanvas(); 89 | loadBm(); 90 | }; 91 | 92 | function loadImageFromFile(file) { 93 | if (info.isReady) { 94 | clear(); 95 | } 96 | imgElement.file = file; 97 | var reader = new FileReader(); 98 | reader.onload = (function(aImg) { 99 | return function(e) { 100 | aImg.src = e.target.result; 101 | }; 102 | })(imgElement); 103 | reader.readAsDataURL(file); 104 | } 105 | 106 | function loadImageFromUrl(url) { 107 | if (info.isReady) { 108 | clear(); 109 | } 110 | imgElement.src = url; 111 | 112 | } 113 | 114 | function setParameter(obj) { 115 | var key; 116 | for (key in obj) { 117 | if (obj.hasOwnProperty(key)) { 118 | info[key] = obj[key]; 119 | } 120 | } 121 | } 122 | 123 | function loadCanvas() { 124 | imgCanvas.width = imgElement.width; 125 | imgCanvas.height = imgElement.height; 126 | var ctx = imgCanvas.getContext('2d'); 127 | ctx.drawImage(imgElement, 0, 0); 128 | } 129 | 130 | function loadBm() { 131 | var ctx = imgCanvas.getContext('2d'); 132 | bm = new Bitmap(imgCanvas.width, imgCanvas.height); 133 | var imgdataobj = ctx.getImageData(0, 0, bm.w, bm.h); 134 | var l = imgdataobj.data.length, i, j, color; 135 | for (i = 0, j = 0; i < l; i += 4, j++) { 136 | color = 0.2126 * imgdataobj.data[i] + 0.7153 * imgdataobj.data[i + 1] + 137 | 0.0721 * imgdataobj.data[i + 2]; 138 | bm.data[j] = (color < 128 ? 1 : 0); 139 | } 140 | info.isReady = true; 141 | } 142 | 143 | 144 | function bmToPathlist() { 145 | 146 | var bm1 = bm.copy(), 147 | currentPoint = new Point(0, 0), 148 | path; 149 | 150 | function findNext(point) { 151 | var i = bm1.w * point.y + point.x; 152 | while (i < bm1.size && bm1.data[i] !== 1) { 153 | i++; 154 | } 155 | return i < bm1.size && bm1.index(i); 156 | } 157 | 158 | function majority(x, y) { 159 | var i, a, ct; 160 | for (i = 2; i < 5; i++) { 161 | ct = 0; 162 | for (a = -i + 1; a <= i - 1; a++) { 163 | ct += bm1.at(x + a, y + i - 1) ? 1 : -1; 164 | ct += bm1.at(x + i - 1, y + a - 1) ? 1 : -1; 165 | ct += bm1.at(x + a - 1, y - i) ? 1 : -1; 166 | ct += bm1.at(x - i, y + a) ? 1 : -1; 167 | } 168 | if (ct > 0) { 169 | return 1; 170 | } else if (ct < 0) { 171 | return 0; 172 | } 173 | } 174 | return 0; 175 | } 176 | 177 | function findPath(point) { 178 | var path = new Path(), 179 | x = point.x, y = point.y, 180 | dirx = 0, diry = 1, tmp; 181 | 182 | path.sign = bm.at(point.x, point.y) ? "+" : "-"; 183 | 184 | while (1) { 185 | path.pt.push(new Point(x, y)); 186 | if (x > path.maxX) 187 | path.maxX = x; 188 | if (x < path.minX) 189 | path.minX = x; 190 | if (y > path.maxY) 191 | path.maxY = y; 192 | if (y < path.minY) 193 | path.minY = y; 194 | path.len++; 195 | 196 | x += dirx; 197 | y += diry; 198 | path.area -= x * diry; 199 | 200 | if (x === point.x && y === point.y) 201 | break; 202 | 203 | var l = bm1.at(x + (dirx + diry - 1 ) / 2, y + (diry - dirx - 1) / 2); 204 | var r = bm1.at(x + (dirx - diry - 1) / 2, y + (diry + dirx - 1) / 2); 205 | 206 | if (r && !l) { 207 | if (info.turnpolicy === "right" || 208 | (info.turnpolicy === "black" && path.sign === '+') || 209 | (info.turnpolicy === "white" && path.sign === '-') || 210 | (info.turnpolicy === "majority" && majority(x, y)) || 211 | (info.turnpolicy === "minority" && !majority(x, y))) { 212 | tmp = dirx; 213 | dirx = -diry; 214 | diry = tmp; 215 | } else { 216 | tmp = dirx; 217 | dirx = diry; 218 | diry = -tmp; 219 | } 220 | } else if (r) { 221 | tmp = dirx; 222 | dirx = -diry; 223 | diry = tmp; 224 | } else if (!l) { 225 | tmp = dirx; 226 | dirx = diry; 227 | diry = -tmp; 228 | } 229 | } 230 | return path; 231 | } 232 | 233 | function xorPath(path){ 234 | var y1 = path.pt[0].y, 235 | len = path.len, 236 | x, y, maxX, minY, i, j; 237 | for (i = 1; i < len; i++) { 238 | x = path.pt[i].x; 239 | y = path.pt[i].y; 240 | 241 | if (y !== y1) { 242 | minY = y1 < y ? y1 : y; 243 | maxX = path.maxX; 244 | for (j = x; j < maxX; j++) { 245 | bm1.flip(j, minY); 246 | } 247 | y1 = y; 248 | } 249 | } 250 | 251 | } 252 | 253 | while (currentPoint = findNext(currentPoint)) { 254 | 255 | path = findPath(currentPoint); 256 | 257 | xorPath(path); 258 | 259 | if (path.area > info.turdsize) { 260 | pathlist.push(path); 261 | } 262 | } 263 | 264 | } 265 | 266 | 267 | function processPath() { 268 | 269 | function Quad() { 270 | this.data = [0,0,0,0,0,0,0,0,0]; 271 | } 272 | 273 | Quad.prototype.at = function(x, y) { 274 | return this.data[x * 3 + y]; 275 | }; 276 | 277 | function Sum(x, y, xy, x2, y2) { 278 | this.x = x; 279 | this.y = y; 280 | this.xy = xy; 281 | this.x2 = x2; 282 | this.y2 = y2; 283 | } 284 | 285 | function mod(a, n) { 286 | return a >= n ? a % n : a>=0 ? a : n-1-(-1-a) % n; 287 | } 288 | 289 | function xprod(p1, p2) { 290 | return p1.x * p2.y - p1.y * p2.x; 291 | } 292 | 293 | function cyclic(a, b, c) { 294 | if (a <= c) { 295 | return (a <= b && b < c); 296 | } else { 297 | return (a <= b || b < c); 298 | } 299 | } 300 | 301 | function sign(i) { 302 | return i > 0 ? 1 : i < 0 ? -1 : 0; 303 | } 304 | 305 | function quadform(Q, w) { 306 | var v = new Array(3), i, j, sum; 307 | 308 | v[0] = w.x; 309 | v[1] = w.y; 310 | v[2] = 1; 311 | sum = 0.0; 312 | 313 | for (i=0; i<3; i++) { 314 | for (j=0; j<3; j++) { 315 | sum += v[i] * Q.at(i, j) * v[j]; 316 | } 317 | } 318 | return sum; 319 | } 320 | 321 | function interval(lambda, a, b) { 322 | var res = new Point(); 323 | 324 | res.x = a.x + lambda * (b.x - a.x); 325 | res.y = a.y + lambda * (b.y - a.y); 326 | return res; 327 | } 328 | 329 | function dorth_infty(p0, p2) { 330 | var r = new Point(); 331 | 332 | r.y = sign(p2.x - p0.x); 333 | r.x = -sign(p2.y - p0.y); 334 | 335 | return r; 336 | } 337 | 338 | function ddenom(p0, p2) { 339 | var r = dorth_infty(p0, p2); 340 | 341 | return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y); 342 | } 343 | 344 | function dpara(p0, p1, p2) { 345 | var x1, y1, x2, y2; 346 | 347 | x1 = p1.x - p0.x; 348 | y1 = p1.y - p0.y; 349 | x2 = p2.x - p0.x; 350 | y2 = p2.y - p0.y; 351 | 352 | return x1 * y2 - x2 * y1; 353 | } 354 | 355 | function cprod(p0, p1, p2, p3) { 356 | var x1, y1, x2, y2; 357 | 358 | x1 = p1.x - p0.x; 359 | y1 = p1.y - p0.y; 360 | x2 = p3.x - p2.x; 361 | y2 = p3.y - p2.y; 362 | 363 | return x1 * y2 - x2 * y1; 364 | } 365 | 366 | function iprod(p0, p1, p2) { 367 | var x1, y1, x2, y2; 368 | 369 | x1 = p1.x - p0.x; 370 | y1 = p1.y - p0.y; 371 | x2 = p2.x - p0.x; 372 | y2 = p2.y - p0.y; 373 | 374 | return x1*x2 + y1*y2; 375 | } 376 | 377 | function iprod1(p0, p1, p2, p3) { 378 | var x1, y1, x2, y2; 379 | 380 | x1 = p1.x - p0.x; 381 | y1 = p1.y - p0.y; 382 | x2 = p3.x - p2.x; 383 | y2 = p3.y - p2.y; 384 | 385 | return x1 * x2 + y1 * y2; 386 | } 387 | 388 | function ddist(p, q) { 389 | return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y)); 390 | } 391 | 392 | function bezier(t, p0, p1, p2, p3) { 393 | var s = 1 - t, res = new Point(); 394 | 395 | res.x = s*s*s*p0.x + 3*(s*s*t)*p1.x + 3*(t*t*s)*p2.x + t*t*t*p3.x; 396 | res.y = s*s*s*p0.y + 3*(s*s*t)*p1.y + 3*(t*t*s)*p2.y + t*t*t*p3.y; 397 | 398 | return res; 399 | } 400 | 401 | function tangent(p0, p1, p2, p3, q0, q1) { 402 | var A, B, C, a, b, c, d, s, r1, r2; 403 | 404 | A = cprod(p0, p1, q0, q1); 405 | B = cprod(p1, p2, q0, q1); 406 | C = cprod(p2, p3, q0, q1); 407 | 408 | a = A - 2 * B + C; 409 | b = -2 * A + 2 * B; 410 | c = A; 411 | 412 | d = b * b - 4 * a * c; 413 | 414 | if (a===0 || d<0) { 415 | return -1.0; 416 | } 417 | 418 | s = Math.sqrt(d); 419 | 420 | r1 = (-b + s) / (2 * a); 421 | r2 = (-b - s) / (2 * a); 422 | 423 | if (r1 >= 0 && r1 <= 1) { 424 | return r1; 425 | } else if (r2 >= 0 && r2 <= 1) { 426 | return r2; 427 | } else { 428 | return -1.0; 429 | } 430 | } 431 | 432 | function calcSums(path) { 433 | var i, x, y; 434 | path.x0 = path.pt[0].x; 435 | path.y0 = path.pt[0].y; 436 | 437 | path.sums = []; 438 | var s = path.sums; 439 | s.push(new Sum(0, 0, 0, 0, 0)); 440 | for(i = 0; i < path.len; i++){ 441 | x = path.pt[i].x - path.x0; 442 | y = path.pt[i].y - path.y0; 443 | s.push(new Sum(s[i].x + x, s[i].y + y, s[i].xy + x * y, 444 | s[i].x2 + x * x, s[i].y2 + y * y)); 445 | } 446 | } 447 | 448 | function calcLon(path) { 449 | 450 | var n = path.len, pt = path.pt, dir, 451 | pivk = new Array(n), 452 | nc = new Array(n), 453 | ct = new Array(4); 454 | path.lon = new Array(n); 455 | 456 | var constraint = [new Point(), new Point()], 457 | cur = new Point(), 458 | off = new Point(), 459 | dk = new Point(), 460 | foundk; 461 | 462 | var i, j, k1, a, b, c, d, k = 0; 463 | for(i = n - 1; i >= 0; i--){ 464 | if (pt[i].x != pt[k].x && pt[i].y != pt[k].y) { 465 | k = i + 1; 466 | } 467 | nc[i] = k; 468 | } 469 | 470 | for (i = n - 1; i >= 0; i--) { 471 | ct[0] = ct[1] = ct[2] = ct[3] = 0; 472 | dir = (3 + 3 * (pt[mod(i + 1, n)].x - pt[i].x) + 473 | (pt[mod(i + 1, n)].y - pt[i].y)) / 2; 474 | ct[dir]++; 475 | 476 | constraint[0].x = 0; 477 | constraint[0].y = 0; 478 | constraint[1].x = 0; 479 | constraint[1].y = 0; 480 | 481 | k = nc[i]; 482 | k1 = i; 483 | while (1) { 484 | foundk = 0; 485 | dir = (3 + 3 * sign(pt[k].x - pt[k1].x) + 486 | sign(pt[k].y - pt[k1].y)) / 2; 487 | ct[dir]++; 488 | 489 | if (ct[0] && ct[1] && ct[2] && ct[3]) { 490 | pivk[i] = k1; 491 | foundk = 1; 492 | break; 493 | } 494 | 495 | cur.x = pt[k].x - pt[i].x; 496 | cur.y = pt[k].y - pt[i].y; 497 | 498 | if (xprod(constraint[0], cur) < 0 || xprod(constraint[1], cur) > 0) { 499 | break; 500 | } 501 | 502 | if (Math.abs(cur.x) <= 1 && Math.abs(cur.y) <= 1) { 503 | 504 | } else { 505 | off.x = cur.x + ((cur.y >= 0 && (cur.y > 0 || cur.x < 0)) ? 1 : -1); 506 | off.y = cur.y + ((cur.x <= 0 && (cur.x < 0 || cur.y < 0)) ? 1 : -1); 507 | if (xprod(constraint[0], off) >= 0) { 508 | constraint[0].x = off.x; 509 | constraint[0].y = off.y; 510 | } 511 | off.x = cur.x + ((cur.y <= 0 && (cur.y < 0 || cur.x < 0)) ? 1 : -1); 512 | off.y = cur.y + ((cur.x >= 0 && (cur.x > 0 || cur.y < 0)) ? 1 : -1); 513 | if (xprod(constraint[1], off) <= 0) { 514 | constraint[1].x = off.x; 515 | constraint[1].y = off.y; 516 | } 517 | } 518 | k1 = k; 519 | k = nc[k1]; 520 | if (!cyclic(k, i, k1)) { 521 | break; 522 | } 523 | } 524 | if (foundk === 0) { 525 | dk.x = sign(pt[k].x-pt[k1].x); 526 | dk.y = sign(pt[k].y-pt[k1].y); 527 | cur.x = pt[k1].x - pt[i].x; 528 | cur.y = pt[k1].y - pt[i].y; 529 | 530 | a = xprod(constraint[0], cur); 531 | b = xprod(constraint[0], dk); 532 | c = xprod(constraint[1], cur); 533 | d = xprod(constraint[1], dk); 534 | 535 | j = 10000000; 536 | if (b < 0) { 537 | j = Math.floor(a / -b); 538 | } 539 | if (d > 0) { 540 | j = Math.min(j, Math.floor(-c / d)); 541 | } 542 | pivk[i] = mod(k1+j,n); 543 | } 544 | } 545 | 546 | j=pivk[n-1]; 547 | path.lon[n-1]=j; 548 | for (i=n-2; i>=0; i--) { 549 | if (cyclic(i+1,pivk[i],j)) { 550 | j=pivk[i]; 551 | } 552 | path.lon[i]=j; 553 | } 554 | 555 | for (i=n-1; cyclic(mod(i+1,n),j,path.lon[i]); i--) { 556 | path.lon[i] = j; 557 | } 558 | } 559 | 560 | function bestPolygon(path) { 561 | 562 | function penalty3(path, i, j) { 563 | 564 | var n = path.len, pt = path.pt, sums = path.sums; 565 | var x, y, xy, x2, y2, 566 | k, a, b, c, s, 567 | px, py, ex, ey, 568 | r = 0; 569 | if (j>=n) { 570 | j -= n; 571 | r = 1; 572 | } 573 | 574 | if (r === 0) { 575 | x = sums[j+1].x - sums[i].x; 576 | y = sums[j+1].y - sums[i].y; 577 | x2 = sums[j+1].x2 - sums[i].x2; 578 | xy = sums[j+1].xy - sums[i].xy; 579 | y2 = sums[j+1].y2 - sums[i].y2; 580 | k = j+1 - i; 581 | } else { 582 | x = sums[j+1].x - sums[i].x + sums[n].x; 583 | y = sums[j+1].y - sums[i].y + sums[n].y; 584 | x2 = sums[j+1].x2 - sums[i].x2 + sums[n].x2; 585 | xy = sums[j+1].xy - sums[i].xy + sums[n].xy; 586 | y2 = sums[j+1].y2 - sums[i].y2 + sums[n].y2; 587 | k = j+1 - i + n; 588 | } 589 | 590 | px = (pt[i].x + pt[j].x) / 2.0 - pt[0].x; 591 | py = (pt[i].y + pt[j].y) / 2.0 - pt[0].y; 592 | ey = (pt[j].x - pt[i].x); 593 | ex = -(pt[j].y - pt[i].y); 594 | 595 | a = ((x2 - 2*x*px) / k + px*px); 596 | b = ((xy - x*py - y*px) / k + px*py); 597 | c = ((y2 - 2*y*py) / k + py*py); 598 | 599 | s = ex*ex*a + 2*ex*ey*b + ey*ey*c; 600 | 601 | return Math.sqrt(s); 602 | } 603 | 604 | var i, j, m, k, 605 | n = path.len, 606 | pen = new Array(n + 1), 607 | prev = new Array(n + 1), 608 | clip0 = new Array(n), 609 | clip1 = new Array(n + 1), 610 | seg0 = new Array (n + 1), 611 | seg1 = new Array(n + 1), 612 | thispen, best, c; 613 | 614 | for (i=0; i0; j--) { 644 | seg1[j] = i; 645 | i = clip1[i]; 646 | } 647 | seg1[0] = 0; 648 | 649 | pen[0]=0; 650 | for (j=1; j<=m; j++) { 651 | for (i=seg1[j]; i<=seg0[j]; i++) { 652 | best = -1; 653 | for (k=seg0[j-1]; k>=clip1[i]; k--) { 654 | thispen = penalty3(path, k, i) + pen[k]; 655 | if (best < 0 || thispen < best) { 656 | prev[i] = k; 657 | best = thispen; 658 | } 659 | } 660 | pen[i] = best; 661 | } 662 | } 663 | path.m = m; 664 | path.po = new Array(m); 665 | 666 | for (i=n, j=m-1; i>0; j--) { 667 | i = prev[i]; 668 | path.po[j] = i; 669 | } 670 | } 671 | 672 | function adjustVertices(path) { 673 | 674 | function pointslope(path, i, j, ctr, dir) { 675 | 676 | var n = path.len, sums = path.sums, 677 | x, y, x2, xy, y2, 678 | k, a, b, c, lambda2, l, r=0; 679 | 680 | while (j>=n) { 681 | j-=n; 682 | r+=1; 683 | } 684 | while (i>=n) { 685 | i-=n; 686 | r-=1; 687 | } 688 | while (j<0) { 689 | j+=n; 690 | r-=1; 691 | } 692 | while (i<0) { 693 | i+=n; 694 | r+=1; 695 | } 696 | 697 | x = sums[j+1].x-sums[i].x+r*sums[n].x; 698 | y = sums[j+1].y-sums[i].y+r*sums[n].y; 699 | x2 = sums[j+1].x2-sums[i].x2+r*sums[n].x2; 700 | xy = sums[j+1].xy-sums[i].xy+r*sums[n].xy; 701 | y2 = sums[j+1].y2-sums[i].y2+r*sums[n].y2; 702 | k = j+1-i+r*n; 703 | 704 | ctr.x = x/k; 705 | ctr.y = y/k; 706 | 707 | a = (x2-x*x/k)/k; 708 | b = (xy-x*y/k)/k; 709 | c = (y2-y*y/k)/k; 710 | 711 | lambda2 = (a+c+Math.sqrt((a-c)*(a-c)+4*b*b))/2; 712 | 713 | a -= lambda2; 714 | c -= lambda2; 715 | 716 | if (Math.abs(a) >= Math.abs(c)) { 717 | l = Math.sqrt(a*a+b*b); 718 | if (l!==0) { 719 | dir.x = -b/l; 720 | dir.y = a/l; 721 | } 722 | } else { 723 | l = Math.sqrt(c*c+b*b); 724 | if (l!==0) { 725 | dir.x = -c/l; 726 | dir.y = b/l; 727 | } 728 | } 729 | if (l===0) { 730 | dir.x = dir.y = 0; 731 | } 732 | } 733 | 734 | var m = path.m, po = path.po, n = path.len, pt = path.pt, 735 | x0 = path.x0, y0 = path.y0, 736 | ctr = new Array(m), dir = new Array(m), 737 | q = new Array(m), 738 | v = new Array(3), d, i, j, k, l, 739 | s = new Point(); 740 | 741 | path.curve = new Curve(m); 742 | 743 | for (i=0; iQ.at(1, 1)) { 798 | v[0] = -Q.at(0, 1); 799 | v[1] = Q.at(0, 0); 800 | } else if (Q.at(1, 1)) { 801 | v[0] = -Q.at(1, 1); 802 | v[1] = Q.at(1, 0); 803 | } else { 804 | v[0] = 1; 805 | v[1] = 0; 806 | } 807 | d = v[0] * v[0] + v[1] * v[1]; 808 | v[2] = - v[1] * s.y - v[0] * s.x; 809 | for (l=0; l<3; l++) { 810 | for (k=0; k<3; k++) { 811 | Q.data[l * 3 + k] += v[l] * v[k] / d; 812 | } 813 | } 814 | } 815 | dx = Math.abs(w.x-s.x); 816 | dy = Math.abs(w.y-s.y); 817 | if (dx <= 0.5 && dy <= 0.5) { 818 | path.curve.vertex[i] = new Point(w.x+x0, w.y+y0); 819 | continue; 820 | } 821 | 822 | min = quadform(Q, s); 823 | xmin = s.x; 824 | ymin = s.y; 825 | 826 | if (Q.at(0, 0) !== 0.0) { 827 | for (z=0; z<2; z++) { 828 | w.y = s.y-0.5+z; 829 | w.x = - (Q.at(0, 1) * w.y + Q.at(0, 2)) / Q.at(0, 0); 830 | dx = Math.abs(w.x-s.x); 831 | cand = quadform(Q, w); 832 | if (dx <= 0.5 && cand < min) { 833 | min = cand; 834 | xmin = w.x; 835 | ymin = w.y; 836 | } 837 | } 838 | } 839 | 840 | if (Q.at(1, 1) !== 0.0) { 841 | for (z=0; z<2; z++) { 842 | w.x = s.x-0.5+z; 843 | w.y = - (Q.at(1, 0) * w.x + Q.at(1, 2)) / Q.at(1, 1); 844 | dy = Math.abs(w.y-s.y); 845 | cand = quadform(Q, w); 846 | if (dy <= 0.5 && cand < min) { 847 | min = cand; 848 | xmin = w.x; 849 | ymin = w.y; 850 | } 851 | } 852 | } 853 | 854 | for (l=0; l<2; l++) { 855 | for (k=0; k<2; k++) { 856 | w.x = s.x-0.5+l; 857 | w.y = s.y-0.5+k; 858 | cand = quadform(Q, w); 859 | if (cand < min) { 860 | min = cand; 861 | xmin = w.x; 862 | ymin = w.y; 863 | } 864 | } 865 | } 866 | 867 | path.curve.vertex[i] = new Point(xmin + x0, ymin + y0); 868 | } 869 | } 870 | 871 | function reverse(path) { 872 | var curve = path.curve, m = curve.n, v = curve.vertex, i, j, tmp; 873 | 874 | for (i=0, j=m-1; i1 ? (1 - 1.0/dd) : 0; 897 | alpha = alpha / 0.75; 898 | } else { 899 | alpha = 4/3.0; 900 | } 901 | curve.alpha0[j] = alpha; 902 | 903 | if (alpha >= info.alphamax) { 904 | curve.tag[j] = "CORNER"; 905 | curve.c[3 * j + 1] = curve.vertex[j]; 906 | curve.c[3 * j + 2] = p4; 907 | } else { 908 | if (alpha < 0.55) { 909 | alpha = 0.55; 910 | } else if (alpha > 1) { 911 | alpha = 1; 912 | } 913 | p2 = interval(0.5+0.5*alpha, curve.vertex[i], curve.vertex[j]); 914 | p3 = interval(0.5+0.5*alpha, curve.vertex[k], curve.vertex[j]); 915 | curve.tag[j] = "CURVE"; 916 | curve.c[3 * j + 0] = p2; 917 | curve.c[3 * j + 1] = p3; 918 | curve.c[3 * j + 2] = p4; 919 | } 920 | curve.alpha[j] = alpha; 921 | curve.beta[j] = 0.5; 922 | } 923 | curve.alphacurve = 1; 924 | } 925 | 926 | function optiCurve(path) { 927 | function Opti(){ 928 | this.pen = 0; 929 | this.c = [new Point(), new Point()]; 930 | this.t = 0; 931 | this.s = 0; 932 | this.alpha = 0; 933 | } 934 | 935 | function opti_penalty(path, i, j, res, opttolerance, convc, areac) { 936 | var m = path.curve.n, curve = path.curve, vertex = curve.vertex, 937 | k, k1, k2, conv, i1, 938 | area, alpha, d, d1, d2, 939 | p0, p1, p2, p3, pt, 940 | A, R, A1, A2, A3, A4, 941 | s, t; 942 | 943 | if (i==j) { 944 | return 1; 945 | } 946 | 947 | k = i; 948 | i1 = mod(i+1, m); 949 | k1 = mod(k+1, m); 950 | conv = convc[k1]; 951 | if (conv === 0) { 952 | return 1; 953 | } 954 | d = ddist(vertex[i], vertex[i1]); 955 | for (k=k1; k!=j; k=k1) { 956 | k1 = mod(k+1, m); 957 | k2 = mod(k+2, m); 958 | if (convc[k1] != conv) { 959 | return 1; 960 | } 961 | if (sign(cprod(vertex[i], vertex[i1], vertex[k1], vertex[k2])) != 962 | conv) { 963 | return 1; 964 | } 965 | if (iprod1(vertex[i], vertex[i1], vertex[k1], vertex[k2]) < 966 | d * ddist(vertex[k1], vertex[k2]) * -0.999847695156) { 967 | return 1; 968 | } 969 | } 970 | 971 | p0 = curve.c[mod(i,m) * 3 + 2].copy(); 972 | p1 = vertex[mod(i+1,m)].copy(); 973 | p2 = vertex[mod(j,m)].copy(); 974 | p3 = curve.c[mod(j,m) * 3 + 2].copy(); 975 | 976 | area = areac[j] - areac[i]; 977 | area -= dpara(vertex[0], curve.c[i * 3 + 2], curve.c[j * 3 + 2])/2; 978 | if (i>=j) { 979 | area += areac[m]; 980 | } 981 | 982 | A1 = dpara(p0, p1, p2); 983 | A2 = dpara(p0, p1, p3); 984 | A3 = dpara(p0, p2, p3); 985 | 986 | A4 = A1+A3-A2; 987 | 988 | if (A2 == A1) { 989 | return 1; 990 | } 991 | 992 | t = A3/(A3-A4); 993 | s = A2/(A2-A1); 994 | A = A2 * t / 2.0; 995 | 996 | if (A === 0.0) { 997 | return 1; 998 | } 999 | 1000 | R = area / A; 1001 | alpha = 2 - Math.sqrt(4 - R / 0.3); 1002 | 1003 | res.c[0] = interval(t * alpha, p0, p1); 1004 | res.c[1] = interval(s * alpha, p3, p2); 1005 | res.alpha = alpha; 1006 | res.t = t; 1007 | res.s = s; 1008 | 1009 | p1 = res.c[0].copy(); 1010 | p2 = res.c[1].copy(); 1011 | 1012 | res.pen = 0; 1013 | 1014 | for (k=mod(i+1,m); k!=j; k=k1) { 1015 | k1 = mod(k+1,m); 1016 | t = tangent(p0, p1, p2, p3, vertex[k], vertex[k1]); 1017 | if (t<-0.5) { 1018 | return 1; 1019 | } 1020 | pt = bezier(t, p0, p1, p2, p3); 1021 | d = ddist(vertex[k], vertex[k1]); 1022 | if (d === 0.0) { 1023 | return 1; 1024 | } 1025 | d1 = dpara(vertex[k], vertex[k1], pt) / d; 1026 | if (Math.abs(d1) > opttolerance) { 1027 | return 1; 1028 | } 1029 | if (iprod(vertex[k], vertex[k1], pt) < 0 || 1030 | iprod(vertex[k1], vertex[k], pt) < 0) { 1031 | return 1; 1032 | } 1033 | res.pen += d1 * d1; 1034 | } 1035 | 1036 | for (k=i; k!=j; k=k1) { 1037 | k1 = mod(k+1,m); 1038 | t = tangent(p0, p1, p2, p3, curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]); 1039 | if (t<-0.5) { 1040 | return 1; 1041 | } 1042 | pt = bezier(t, p0, p1, p2, p3); 1043 | d = ddist(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]); 1044 | if (d === 0.0) { 1045 | return 1; 1046 | } 1047 | d1 = dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], pt) / d; 1048 | d2 = dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], vertex[k1]) / d; 1049 | d2 *= 0.75 * curve.alpha[k1]; 1050 | if (d2 < 0) { 1051 | d1 = -d1; 1052 | d2 = -d2; 1053 | } 1054 | if (d1 < d2 - opttolerance) { 1055 | return 1; 1056 | } 1057 | if (d1 < d2) { 1058 | res.pen += (d1 - d2) * (d1 - d2); 1059 | } 1060 | } 1061 | 1062 | return 0; 1063 | } 1064 | 1065 | var curve = path.curve, m = curve.n, vert = curve.vertex, 1066 | pt = new Array(m + 1), 1067 | pen = new Array(m + 1), 1068 | len = new Array(m + 1), 1069 | opt = new Array(m + 1), 1070 | om, i,j,r, 1071 | o = new Opti(), p0, 1072 | i1, area, alpha, ocurve, 1073 | s, t; 1074 | 1075 | var convc = new Array(m), areac = new Array(m + 1); 1076 | 1077 | for (i=0; i=0; i--) { 1110 | r = opti_penalty(path, i, mod(j,m), o, info.opttolerance, convc, 1111 | areac); 1112 | if (r) { 1113 | break; 1114 | } 1115 | if (len[j] > len[i]+1 || 1116 | (len[j] == len[i]+1 && pen[j] > pen[i] + o.pen)) { 1117 | pt[j] = i; 1118 | pen[j] = pen[i] + o.pen; 1119 | len[j] = len[i] + 1; 1120 | opt[j] = o; 1121 | o = new Opti(); 1122 | } 1123 | } 1124 | } 1125 | om = len[m]; 1126 | ocurve = new Curve(om); 1127 | s = new Array(om); 1128 | t = new Array(om); 1129 | 1130 | j = m; 1131 | for (i=om-1; i>=0; i--) { 1132 | if (pt[j]==j-1) { 1133 | ocurve.tag[i] = curve.tag[mod(j,m)]; 1134 | ocurve.c[i * 3 + 0] = curve.c[mod(j,m) * 3 + 0]; 1135 | ocurve.c[i * 3 + 1] = curve.c[mod(j,m) * 3 + 1]; 1136 | ocurve.c[i * 3 + 2] = curve.c[mod(j,m) * 3 + 2]; 1137 | ocurve.vertex[i] = curve.vertex[mod(j,m)]; 1138 | ocurve.alpha[i] = curve.alpha[mod(j,m)]; 1139 | ocurve.alpha0[i] = curve.alpha0[mod(j,m)]; 1140 | ocurve.beta[i] = curve.beta[mod(j,m)]; 1141 | s[i] = t[i] = 1.0; 1142 | } else { 1143 | ocurve.tag[i] = "CURVE"; 1144 | ocurve.c[i * 3 + 0] = opt[j].c[0]; 1145 | ocurve.c[i * 3 + 1] = opt[j].c[1]; 1146 | ocurve.c[i * 3 + 2] = curve.c[mod(j,m) * 3 + 2]; 1147 | ocurve.vertex[i] = interval(opt[j].s, curve.c[mod(j,m) * 3 + 2], 1148 | vert[mod(j,m)]); 1149 | ocurve.alpha[i] = opt[j].alpha; 1150 | ocurve.alpha0[i] = opt[j].alpha; 1151 | s[i] = opt[j].s; 1152 | t[i] = opt[j].t; 1153 | } 1154 | j = pt[j]; 1155 | } 1156 | 1157 | for (i=0; i'; 1247 | svg += ''; 1262 | return svg; 1263 | } 1264 | 1265 | return{ 1266 | loadImageFromFile: loadImageFromFile, 1267 | loadImageFromUrl: loadImageFromUrl, 1268 | setParameter: setParameter, 1269 | process: process, 1270 | getSVG: getSVG, 1271 | img: imgElement 1272 | }; 1273 | }; 1274 | --------------------------------------------------------------------------------