MetalCanvas is a Swift library for rendering Metal shaders on macOS and iOS, inspired by glsl-canvas.
demo.mov
- Easy-to-use Metal shader rendering
- Built-in uniforms (time, resolution, mouse, date)
- Texture support
- SwiftUI integration
- Timer controls (play, pause, toggle)
- Cross-platform (macOS 14+, iOS 17+)
- In Xcode, select File > Add Package Dependencies...
- Enter the repository URL:
https://github.com/NakaokaRei/MetalCanvas.git - For Dependency Rule, select Branch and enter
master - Click Add Package
Add MetalCanvas to your Package.swift file:
dependencies: [
.package(url: "https://github.com/NakaokaRei/MetalCanvas.git", branch: "master")
]Then add MetalCanvas to your target's dependencies:
targets: [
.target(
name: "YourTarget",
dependencies: ["MetalCanvas"]
)
]import SwiftUI
import MetalCanvas
struct ContentView: View {
@State private var fragmentShader: String? = """
#include <metal_stdlib>
using namespace metal;
struct FragmentUniforms {
float2 u_resolution;
float u_time;
float2 u_mouse;
float4 u_date;
};
struct VertexOut {
float4 position [[position]];
float2 texCoord;
};
fragment float4 fragment_main(VertexOut in [[stage_in]],
constant FragmentUniforms& uniforms [[buffer(0)]]) {
float2 uv = in.texCoord;
float3 color = float3(uv.x, uv.y, 0.5 + 0.5 * sin(uniforms.u_time));
return float4(color, 1.0);
}
"""
var body: some View {
MetalCanvasView(fragmentShader: $fragmentShader)
.frame(width: 400, height: 400)
}
}u_resolution- Viewport resolution (width, height) in pixelsu_time- Time in seconds since render startedu_mouse- Mouse position in pixelsu_date- Current date (year, month, day, seconds since midnight)
MetalCanvas expects shaders written in Metal Shading Language. The fragment shader should include:
#include <metal_stdlib>
using namespace metal;
struct FragmentUniforms {
float2 u_resolution;
float u_time;
float2 u_mouse;
float4 u_date;
};
struct VertexOut {
float4 position [[position]];
float2 texCoord;
};
fragment float4 fragment_main(VertexOut in [[stage_in]],
constant FragmentUniforms& uniforms [[buffer(0)]]) {
// Your shader code here
return float4(color, 1.0);
}Check out the example apps in the Example directory:
Located in Example/MetalCanvasExample-macOS/:
- Interactive shader editor with live preview
- Built-in shader examples (gradient, circles, plasma, mandelbrot, waves, voronoi)
- Play/pause controls
- Code editor with syntax highlighting
Located in Example/MetalCanvasExample-iOS/:
- Shader gallery with segmented picker
- Same built-in shader examples as macOS
- Optimized for touch interface
To run the examples:
- Open
Example/MetalCanvasExamples.xcworkspace - Select either
MetalCanvasExample(macOS) orMetalCanvasExample-iOSscheme - Build and run
- macOS 14.0+ / iOS 17.0+
- Swift 5.9+
MIT License