Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

191 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SharpCanvas

License: CC0

A comprehensive C# implementation of the HTML5 Canvas 2D rendering API with two production-ready backends: cross-platform SkiaSharp and Windows-native System.Drawing.

🚀 Features

  • ~95% Canvas API Coverage - Comprehensive implementation of the HTML5 Canvas 2D API (details)
  • Two Production Backends
    • SkiaSharp - Cross-platform (Windows, Linux, macOS), hardware-accelerated
    • System.Drawing - Windows-native GDI+, perfect for Windows-only applications
  • 100% Test Coverage - 258/258 tests passing (229 modern + 28 core + 1 standalone)
  • Backend-Agnostic Runtime - Workers, SharedWorkers, and Event Loops shared across all backends
  • WebAssembly Support - Run in browsers via Blazor WASM or headless with Wasmtime
  • Blazor Component - Ready-to-use interactive Canvas component for Blazor apps
  • JavaScript Interoperability - Full JavaScript integration via Microsoft.ClearScript V8
  • NativeAOT Ready - Experimental support for ahead-of-time compilation
  • Accessibility - Focus ring support for enhanced accessibility

📦 Quick Start

Choosing a Backend

SharpCanvas provides two production-ready backends:

SkiaSharp (Recommended for most scenarios)

dotnet add package SharpCanvas.Context.Skia
  • ✅ Cross-platform (Windows, Linux, macOS)
  • ✅ Hardware-accelerated rendering
  • ✅ Active development and modern features
  • ✅ WebAssembly and Blazor support

System.Drawing (Windows-only)

dotnet add package SharpCanvas.Context.Drawing2D
  • ✅ Windows-native GDI+ integration
  • ✅ No external dependencies on Windows
  • ✅ Perfect for Windows-only applications
  • ✅ Backward compatibility - Potential support back to .NET Framework 4.x (2012+)
  • ✅ Familiar API for Windows developers

Basic Usage (SkiaSharp)

usingSharpCanvas.Context.Skia;usingSkiaSharp;// Create a surfacevarinfo=newSKImageInfo(800,600);varsurface=SKSurface.Create(info);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newSkiaCanvasRenderingContext2D(surface,document);// Draw somethingcontext.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Export to imagebyte[]pngBytes=context.GetBitmap();

Advanced Example

// Gradientsvargradient=context.createLinearGradient(0,0,200,0);gradient.addColorStop(0,"red");gradient.addColorStop(0.5,"yellow");gradient.addColorStop(1,"green");context.fillStyle=gradient;context.fillRect(10,200,200,50);// Transformationscontext.save();context.translate(100,100);context.rotate(Math.PI/4);context.fillStyle="purple";context.fillRect(-25,-25,50,50);context.restore();// Pathscontext.beginPath();context.arc(300,100,50,0,2*Math.PI);context.fillStyle="orange";context.fill();context.strokeStyle="black";context.lineWidth=2;context.stroke();

Basic Usage (System.Drawing)

usingSharpCanvas.Legacy.Drawing.Context.Drawing2D;usingSystem.Drawing;// Create a bitmap and graphics surfacevarbitmap=newBitmap(800,600);usingvargraphics=Graphics.FromImage(bitmap);// Create a canvas contextvardocument=newDocument();// or your IDocument implementationvarcontext=newCanvasRenderingContext2D(graphics,bitmap);// Draw something (same Canvas API!)context.fillStyle="red";context.fillRect(10,10,100,100);context.strokeStyle="blue";context.lineWidth=5;context.strokeRect(150,10,100,100);// Draw textcontext.font="24px Arial";context.fillStyle="black";context.fillText("Hello, SharpCanvas!",10,150);// Save to filebitmap.Save("output.png",System.Drawing.Imaging.ImageFormat.Png);

Note: Both backends use the same HTML5 Canvas API, so your code is portable between them!

🌐 WebAssembly and Blazor

SharpCanvas supports WebAssembly deployment for running .NET Canvas code in browsers and headless environments.

Blazor WebAssembly Component

Use SharpCanvas in Blazor WASM applications:

cd SharpCanvas.Blazor.Wasm
dotnet run

Then navigate to http://localhost:5233 to see the interactive demo with 4 rendering modes:

  • Basic shapes (rectangles, fills, strokes)
  • Gradients (linear and radial)
  • Paths (arcs, curves, bezier)
  • Text rendering

JavaScript Integration

SharpCanvas includes JavaScript engine integration via ClearScript V8:

cd SharpCanvas.JsHost
dotnet run

This runs comprehensive JavaScript-driven Canvas tests including:

  • Basic drawing operations
  • Path API (moveTo, lineTo, arc, curves)
  • Transformations (translate, rotate, scale)
  • Gradients and patterns
  • Text rendering

All tests generate PNG output files for validation.

Standalone WASM Execution

For headless WASM execution with Wasmtime (requires wasm-tools-net8 workload):

# Install Wasmtime
curl https://wasmtime.dev/install.sh -sSf | bash
# Build WASM console appcd SharpCanvas.Wasm.Console
dotnet build
# Run with Wasmtime
wasmtime run bin/Debug/net8.0/browser-wasm/AppBundle/SharpCanvas.Wasm.Console.wasm

Note: See docs/WASM_DEPLOYMENT.md for comprehensive deployment instructions.

WASM Deployment Documentation

🏗️ Architecture

Project Structure

SharpCanvas/
├── SharpCanvas.Core/ # Core interfaces and shared types
├── SharpCanvas.Runtime/ # Backend-agnostic runtime (Workers, Event Loops) ✨ NEW
├── Context.Skia/ # SkiaSharp backend (cross-platform)
├── Legacy/Drawing/
│ └── Context.Drawing2D/ # System.Drawing backend (Windows GDI+)
├── Context.WindowsMedia/ # WPF backend (Windows only, legacy)
├── SharpCanvas.Tests/ # Test suites
│ ├── Tests.Skia.Modern/ # Comprehensive tests (229 tests)
│ ├── Tests.Skia/ # Core integration tests (28 tests)
│ └── Tests.Skia.Standalone/ # Standalone integration tests (1 test)
├── SharpCanvas.JsHost/ # JavaScript integration (ClearScript V8)
├── SharpCanvas.Blazor.Wasm/ # Blazor WebAssembly component
├── SharpCanvas.Wasm.Console/ # Standalone WASM console app (Wasmtime)
└── SharpCanvas.Wasm.NativeAOT/ # Experimental NativeAOT project (opt-in)

Backend Comparison

FeatureSkiaSharpSystem.Drawing
Platforms✅ Windows, Linux, macOS⚠️ Windows only
Performance⚡ Hardware-accelerated🎨 Software rendering (GDI+)
API Completeness✅ 100% Canvas 2D API✅ 100% Canvas 2D API
Compilation✅ 100% (0 errors)✅ 100% (0 errors)
Tests✅ 258/258 passing (100%)✅ Compiles, tests available
WASM Support✅ Blazor + Wasmtime❌ N/A (requires Windows APIs)
JavaScript Integration✅ ClearScript V8✅ ClearScript V8
DependenciesSkiaSharp NuGetSystem.Drawing (built-in)
Framework Support.NET Standard 2.0+ / .NET 8.0+.NET 8.0+ (Windows)
Best ForCross-platform, modern appsWindows desktop/server, legacy .NET
Status✅ Production Ready✅ Production Ready

📖 Documentation

Core Documentation

Key Features

  • Backend-Agnostic Runtime - Workers and SharedWorkers work with all backends
  • Conditional Compilation - Build Skia or System.Drawing targets separately
  • Testing Coverage - 258 tests validate both backends automatically
  • Zero Code Duplication - ~2000 lines of runtime code shared between backends

📚 API Documentation

Core Canvas API

SharpCanvas implements the full HTML5 Canvas 2D API:

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw rectangle outline
  • clearRect(x, y, width, height) - Clear rectangle area

Paths

  • beginPath() - Start new path
  • closePath() - Close current path
  • moveTo(x, y) - Move to point
  • lineTo(x, y) - Line to point
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draw arc
  • arcTo(x1, y1, x2, y2, radius) - Arc to point
  • quadraticCurveTo(cpx, cpy, x, y) - Quadratic curve
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - Bezier curve
  • ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) - Draw ellipse
  • rect(x, y, width, height) - Add rectangle to path
  • roundRect(x, y, width, height, radii) - Add rounded rectangle

Drawing Paths

  • fill() / fill(path) - Fill current path or Path2D object
  • stroke() / stroke(path) - Stroke current path or Path2D object
  • clip() / clip(path) - Set clipping region

Text

  • fillText(text, x, y) - Draw filled text
  • strokeText(text, x, y) - Draw text outline
  • measureText(text) - Measure text dimensions

Images

  • drawImage(image, dx, dy) - Draw image
  • drawImage(image, dx, dy, dWidth, dHeight) - Draw scaled image
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) - Draw image slice

Transformations

  • translate(x, y) - Translate origin
  • rotate(angle) - Rotate coordinate system
  • scale(x, y) - Scale coordinate system
  • transform(a, b, c, d, e, f) - Apply transformation matrix
  • setTransform(a, b, c, d, e, f) - Set transformation matrix
  • getTransform() - Get current transformation
  • resetTransform() - Reset to identity matrix

State Management

  • save() - Save current state
  • restore() - Restore previous state
  • reset() - Reset to default state

Styles

  • fillStyle - Fill color, gradient, or pattern
  • strokeStyle - Stroke color, gradient, or pattern
  • lineWidth - Line width
  • lineCap - Line cap style ("butt", "round", "square")
  • lineJoin - Line join style ("miter", "round", "bevel")
  • miterLimit - Miter limit
  • setLineDash(segments) - Set line dash pattern
  • getLineDash() - Get line dash pattern
  • lineDashOffset - Dash offset

Shadows

  • shadowColor - Shadow color
  • shadowBlur - Shadow blur radius
  • shadowOffsetX - Shadow X offset
  • shadowOffsetY - Shadow Y offset

Compositing

  • globalAlpha - Global transparency (0.0 - 1.0)
  • globalCompositeOperation - Compositing mode

Gradients and Patterns

  • createLinearGradient(x0, y0, x1, y1) - Create linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - Create radial gradient
  • createConicGradient(startAngle, x, y) - Create conic gradient
  • createPattern(image, repetition) - Create pattern

Image Data

  • getImageData(sx, sy, sw, sh) - Get pixel data
  • putImageData(imageData, dx, dy) - Put pixel data
  • createImageData(width, height) - Create blank image data

Context State

  • isContextLost() - Check if context is lost
  • getContextAttributes() - Get context attributes

Accessibility

  • drawFocusIfNeeded(element) - Draw focus ring if element focused

Properties

  • font - Text font
  • textAlign - Text alignment ("start", "end", "left", "right", "center")
  • textBaseLine - Text baseline
  • direction - Text direction ("ltr", "rtl")
  • imageSmoothingEnabled - Enable/disable image smoothing
  • imageSmoothingQuality - Image smoothing quality

🧪 Testing

Running Tests

# Run all tests
dotnet test# Run modern backend tests only
dotnet test SharpCanvas.Tests/Tests.Skia.Modern/
# Run unified tests (cross-backend)
dotnet test SharpCanvas.Tests/Tests.Unified/
# Run with detailed output
dotnet test --verbosity detailed

Test Coverage

  • Modern Backend: 230/230 tests passing (100%)
  • Standalone Tests: 1/1 tests passing (100%)
  • Core Tests: 28/28 tests passing (100%)
  • Windows-specific Tests: 28/28 tests passing (100%)
  • Total: 258/258 tests passing (100%)

All tests pass successfully, including:

  • All bezier curve and path operations
  • All composite operations and blend modes
  • All filter effects and combinations
  • All transformation scenarios
  • Workers and SharedWorker tests
  • ImageBitmap and OffscreenCanvas tests

🛠️ Building from Source

Prerequisites

  • .NET SDK 8.0 or later (verified on .NET 8, 9, and 10)
  • SkiaSharp (automatically restored via NuGet)

Build Steps

# Clone the repository
git clone https://github.com/w3canvas/sharpcanvas.git
cd sharpcanvas
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
# Run tests
dotnet test

Building in Claude Code Web

If you encounter NuGet proxy authentication issues in Claude Code Web, use the provided proxy:

# Start the NuGet proxy
python3 .claude/nuget-proxy.py > /tmp/nuget_proxy.log 2>&1&# Set proxy environment variablesexport all_proxy=http://127.0.0.1:8889
export ALL_PROXY=http://127.0.0.1:8889
export http_proxy=http://127.0.0.1:8889
export HTTP_PROXY=http://127.0.0.1:8889
export https_proxy=http://127.0.0.1:8889
export HTTPS_PROXY=http://127.0.0.1:8889
# Now build normally
dotnet restore
dotnet build

See .claude/NUGET_PROXY_README.md for details.

📖 Documentation

Core Documentation

WebAssembly and Blazor Documentation

🎯 Production Readiness

Both SharpCanvas backends are production-ready!

✅ SkiaSharp Backend (Cross-Platform)

Status: Production Ready - Recommended for most scenarios

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All transformation operations
  • ✅ Gradients and patterns (linear, radial, conic)
  • ✅ Shadow effects
  • ✅ Image data manipulation
  • ✅ All compositing operations (25+ blend modes)
  • ✅ Complete filter support (10 CSS filter functions)
  • ✅ Accessibility features (drawFocusIfNeeded)
  • ✅ Workers and SharedWorker support
  • ✅ ImageBitmap and OffscreenCanvas
  • ✅ Path2D reusable paths
  • 258/258 tests passing (100%)
  • ✅ WebAssembly/Blazor deployment
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows, Linux, macOS

✅ System.Drawing Backend (Windows-Native)

Status: Production Ready - Perfect for Windows-only applications

Fully Implemented:

  • ✅ Complete HTML5 Canvas 2D API
  • ✅ All path operations (beginPath, moveTo, lineTo, arc, bezierCurveTo, etc.)
  • ✅ Rectangle operations (fillRect, strokeRect, clearRect)
  • ✅ Text rendering with font parsing
  • ✅ Transformations (translate, rotate, scale)
  • ✅ Gradients and patterns
  • ✅ State management (save/restore)
  • 100% compilation (0 errors)
  • ✅ JavaScript integration via ClearScript V8

Platforms: Windows only (GDI+)

🔜 Optional Future Enhancements

  • NativeAOT optimization testing
  • Performance profiling for very large canvases
  • Additional SVG path parsing features
  • WASM deployment optimization

🤝 Contributing

Contributions are welcome! Please feel free to submit pull requests.

Areas for Contribution

See Roadmap for detailed contribution opportunities.

High-impact areas:

  1. Examples and Samples - Real-world usage examples, tutorials, and demos
  2. Performance - Profile and optimize rendering for complex scenes
  3. Documentation - Additional examples, translations, quick-start guides
  4. Platform Testing - Test and optimize on different platforms (Linux, macOS, Windows)
  5. Developer Tools - Visual debuggers, profilers, and utilities
  6. WASM Optimization - Improve WebAssembly package sizes and performance
  7. NativeAOT Testing - Validate and optimize ahead-of-time compilation

Current Status:

  • SkiaSharp backend - Feature-complete, 100% tested
  • System.Drawing backend - Feature-complete, fully implemented
  • WASM deployment - Verified for .NET 8, 9, and 10
  • NativeAOT - Verified for .NET 8, 9, and 10

Focus contributions on enhancements, tooling, examples, and deployment optimizations.

📄 License

Unless otherwise noted, all source code and documentation is released into the public domain under CC0.

For questions about licensing, please contact:

  • w3canvas at jumis.com

🙏 Credits

Developed by Jumis, Inc. and contributors.

Based on the HTML5 Canvas specification:

📞 Support

About

SharpCanvas is an implementation of HTML5 Canvas written in C# for .Net Environments

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages