🎨 AI Coloring Book for Kids

Core Source Code & Educational Canvas Implementation

React 19.1+ TypeScript Gemini AI Canvas API Educational Tech

🔍 About This Code Showcase

This curated code demonstration showcases how the AI Coloring Book creates educational experiences by combining AI-generated content with interactive canvas technology designed specifically for children.

Full deployment configurations, API keys, and proprietary details are omitted for security. This showcase highlights the core educational canvas engine and child-centered AI integration algorithms.

🎨 Core Algorithm: Interactive Canvas Engine

The heart of the AI Coloring Book is its sophisticated canvas system that combines flood-fill algorithms with child-friendly interactions, optimized for educational development and motor skill enhancement:

🖌️ ColoringCanvas.tsx
import React, { useRef, useEffect, useCallback, forwardRef, useImperativeHandle } from 'react'; interface ColoringCanvasProps { imageUrl: string; color: string; onHistoryChange: (canUndo: boolean) => void; } export interface CanvasHandle { undo: () => void; } export const ColoringCanvas = forwardRef( ({ imageUrl, color, onHistoryChange }, ref) => { const canvasRef = useRef(null); const imageRef = useRefnull>(null); const historyRef = useRef([]); // Convert hex colors to RGB for canvas operations const hexToRgb = (hex: string) => { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), } : null; }; // Initialize canvas with AI-generated coloring page useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const context = canvas.getContext('2d', { willReadFrequently: true }); if (!context) return; // Load AI-generated image and optimize for child interaction const img = new Image(); img.crossOrigin = "anonymous"; img.src = imageUrl; img.onload = () => { const parent = canvas.parentElement; if (parent) { // Responsive sizing for different devices (tablets, phones) const size = Math.min(parent.clientWidth, parent.clientHeight); canvas.width = size; canvas.height = size; context.drawImage(img, 0, 0, canvas.width, canvas.height); imageRef.current = img; // Initialize undo system for mistake correction const initialImageData = context.getImageData(0, 0, canvas.width, canvas.height); historyRef.current = [initialImageData]; onHistoryChange(false); } }; }, [imageUrl, onHistoryChange]); // Advanced flood-fill algorithm optimized for educational use const floodFill = useCallback(( ctx: CanvasRenderingContext2D, startX: number, startY: number, fillColor: {r: number, g: number, b: number} ) => { const canvas = ctx.canvas; const { width, height } = canvas; const imageData = ctx.getImageData(0, 0, width, height); const data = imageData.data; const startPos = (startY * width + startX) * 4; const startR = data[startPos]; const startG = data[startPos + 1]; const startB = data[startPos + 2]; // Prevent filling the same color if (startR === fillColor.r && startG === fillColor.g && startB === fillColor.b) { return; } // Smart line detection - preserve black outlines for clear coloring areas const isLine = (r: number, g: number, b: number) => r < 50 && g < 50 && b < 50; if (isLine(startR, startG, startB)) { return; // Don't fill lines - keeps outlines intact } // Color tolerance for child-friendly filling (forgiving touch interaction) const tolerance = 30; const colorMatch = (pos: number) => { const r = data[pos]; const g = data[pos + 1]; const b = data[pos + 2]; return Math.abs(r - startR) <= tolerance && Math.abs(g - startG) <= tolerance && Math.abs(b - startB) <= tolerance; }; // Efficient stack-based flood fill algorithm const pixelStack = [[startX, startY]]; while (pixelStack.length) { const newPos = pixelStack.pop(); if (!newPos) continue; let [x, y] = newPos; let currentPos = (y * width + x) * 4; // Optimize fill pattern for smooth coloring experience while (y-- >= 0 && colorMatch(currentPos)) { currentPos -= width * 4; } currentPos += width * 4; ++y; let reachLeft = false; let reachRight = false; while (y++ < height - 1 && colorMatch(currentPos)) { // Apply color with full opacity for vibrant results data[currentPos] = fillColor.r; data[currentPos + 1] = fillColor.g; data[currentPos + 2] = fillColor.b; data[currentPos + 3] = 255; // Full alpha // Expand fill area intelligently (left and right) if (x > 0) { if (colorMatch(currentPos - 4)) { if (!reachLeft) { pixelStack.push([x - 1, y]); reachLeft = true; } } else if (reachLeft) { reachLeft = false; } } if (x < width - 1) { if (colorMatch(currentPos + 4)) { if (!reachRight) { pixelStack.push([x + 1, y]); reachRight = true; } } else if (reachRight) { reachRight = false; } } currentPos += width * 4; } } ctx.putImageData(imageData, 0, 0); }, []);

🤖 AI Generation Engine: Child-Safe Content Creation

The AI generation system creates educational, age-appropriate coloring pages using Google Gemini's image generation with specialized prompts designed for child development:

🧠 geminiService.ts
import { GoogleGenAI } from "@google/genai"; const API_KEY = process.env.API_KEY; if (!API_KEY) { throw new Error("API_KEY environment variable not set"); } const ai = new GoogleGenAI({ apiKey: API_KEY }); // Educational AI-powered coloring page generation export const generateColoringPage = async (theme: string): Promise => { // Carefully crafted prompt for child-appropriate, educational content const prompt = `A simple, black and white coloring book page for a toddler. The theme is "${theme}". The image must have: - Clear, thick, solid black outlines - Large, easy-to-color areas perfect for developing motor skills - No shading, no grayscale, no complex details - Clean white background for optimal contrast - Age-appropriate, educational content that encourages learning`; try { // Use Gemini's advanced image generation with educational parameters const response = await ai.models.generateImages({ model: 'imagen-4.0-generate-001', prompt: prompt, config: { numberOfImages: 1, outputMimeType: 'image/png', aspectRatio: '1:1', // Square format perfect for tablets // Safety filters ensure child-appropriate content }, }); if (response.generatedImages && response.generatedImages.length > 0) { const base64ImageBytes: string = response.generatedImages[0].image.imageBytes; return base64ImageBytes; } else { throw new Error("No image was generated by the API."); } } catch (error) { console.error("Error generating image with Gemini AI:", error); // Child-friendly error messaging throw new Error("Oops! We couldn't create a picture. Please try another theme."); } };

🎮 Interactive Controls & User Experience

The application state management combines React's modern patterns with child-centered design principles for an intuitive, educational experience:

⚛️ App.tsx - Main Application Logic
import React, { useState, useCallback, useRef } from 'react'; import { ColorPalette } from './components/ColorPalette'; import { ColoringCanvas, CanvasHandle } from './components/ColoringCanvas'; import { ThemeControls } from './components/ThemeControls'; import { generateColoringPage } from './services/geminiService'; const App: React.FC = () => { // Educational state management for child interaction const [theme, setTheme] = useState(''); const [activePrompt, setActivePrompt] = useState(''); const [imageUrl, setImageUrl] = useStatenull>(null); const [selectedColor, setSelectedColor] = useState(COLORS[0]); const [isLoading, setIsLoading] = useState(false); const [canUndo, setCanUndo] = useState(false); const canvasRef = useRef(null); // AI generation with child-friendly error handling const handleGenerate = useCallback(async (currentTheme: string) => { if (!currentTheme || isLoading) return; setIsLoading(true); setError(null); setImageUrl(null); setCanUndo(false); try { // Generate educational content based on child's input const generatedImage = await generateColoringPage(currentTheme); setImageUrl(`data:image/png;base64,${generatedImage}`); setActivePrompt(currentTheme); setCanvasKey(Date.now()); // Reset canvas for new creative session } catch (err) { console.error(err); // Encouraging, non-technical error message for children setError('Oops! We couldn\'t create a picture. Please try another theme.'); } finally { setIsLoading(false); } }, [isLoading]); // Creative control functions designed for child interaction const handleNext = useCallback(() => { if (activePrompt) { setCanUndo(false); handleGenerate(activePrompt); // Generate new variation of same theme } }, [activePrompt, handleGenerate]); const handleRefresh = useCallback(() => { setCanvasKey(Date.now()); // Clear coloring, keep image setCanUndo(false); }, []); const handleUndo = useCallback(() => { canvasRef.current?.undo(); // Mistake forgiveness for learning }, []); return (
"min-h-screen flex flex-col items-center justify-center p-4">
"w-full max-w-5xl mb-4">

"text-4xl md:text-5xl font-bold text-center text-blue-600"> AI Coloring Book

"text-center text-gray-500 mt-1">What do you want to color today?

); };

🎨 Educational Color Palette System

The color palette is carefully designed with child development principles, featuring 12 colors selected for their educational value and psychological impact on young learners:

🌈 constants.ts - Educational Color Design
// 12 carefully selected colors optimized for child development export const COLORS = [ '#FF5252', // Red - Energy and excitement, teaches primary colors '#FF7900', // Orange - Warmth and enthusiasm, secondary color learning '#FFD000', // Yellow - Happiness and brightness, primary color '#4CAF50', // Green - Nature and growth, secondary color '#3498DB', // Blue - Calm and trust, primary color '#9B59B6', // Purple - Creativity and imagination, secondary color '#E91E63', // Pink - Playful and fun, emotional expression '#964B00', // Brown - Earth tones, natural world connection '#212121', // Black - Outlines and definition, contrast learning '#9E9E9E', // Gray - Subtle shading, tone understanding '#FFFFFF', // White - Highlights and space, negative space concept '#00BCD4' // Cyan - Cool accent, color spectrum completion ]; // Color theory education through interactive selection export const COLOR_CATEGORIES = { primary: ['#FF5252', '#FFD000', '#3498DB'], secondary: ['#FF7900', '#4CAF50', '#9B59B6'], neutral: ['#212121', '#9E9E9E', '#FFFFFF'], expressive: ['#E91E63', '#964B00', '#00BCD4'] };

⚙️ Educational Technology Architecture

Child-Centered Design Principles

AI Safety & Educational Integrity

Performance Optimization for Educational Devices