Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 84 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "canvas-rs"
version = "0.1.0"
edition = "2024"

[dependencies]
[workspace]
members = [
"canvas",
"images",
]
resolver = "2"
6 changes: 6 additions & 0 deletions canvas/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "canvas"
version = "0.1.0"
edition = "2021"

[dependencies]
28 changes: 6 additions & 22 deletions src/canvas.rs → canvas/src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,19 @@ use std::rc::Rc;
use crate::color::{parse_color, Color};
use crate::image::ImageData;
use crate::path::{Path, PathCommand};
use crate::png::{base64_encode, encode_png};
use crate::render::{self, LineCap};

// ── Canvas ───────────────────────────────────────────────────────────────────

/// A 2-D drawing surface, analogous to the HTML `<canvas>` element.
///
/// ```
/// use canvas_rs::Canvas;
/// use canvas::Canvas;
///
/// let canvas = Canvas::new(100, 100);
/// let mut ctx = canvas.get_context("2d").unwrap();
/// ctx.set_fill_style("red");
/// ctx.fill_rect(0.0, 0.0, 100.0, 100.0);
/// let _url = canvas.to_data_url();
/// ```
pub struct Canvas {
pub(crate) width: u32,
Expand Down Expand Up @@ -56,25 +54,6 @@ impl Canvas {
})
}

/// Encode the canvas contents as a `data:image/png;base64,...` URL.
///
/// The optional `type_` parameter is accepted for API compatibility but
/// only `"image/png"` is supported. The `quality` parameter is ignored
/// for PNG.
pub fn to_data_url(&self) -> String {
self.to_data_url_with_options("image/png", 1.0)
}

pub fn to_data_url_with_type(&self, type_: &str) -> String {
self.to_data_url_with_options(type_, 1.0)
}

pub fn to_data_url_with_options(&self, _type_: &str, _quality: f64) -> String {
let buf = self.buffer.borrow();
let png = encode_png(self.width, self.height, &buf);
format!("data:image/png;base64,{}", base64_encode(&png))
}

/// Return the canvas width in pixels.
pub fn width(&self) -> u32 {
self.width
Expand All @@ -89,6 +68,11 @@ impl Canvas {
pub fn get_image_data(&self) -> ImageData {
ImageData::from_rgba(self.width, self.height, self.buffer.borrow().clone())
}

/// Borrow the raw RGBA pixel buffer.
pub fn pixels(&self) -> std::cell::Ref<'_, Vec<u8>> {
self.buffer.borrow()
}
}

// ── Context2D ────────────────────────────────────────────────────────────────
Expand Down
File renamed without changes.
File renamed without changes.
11 changes: 4 additions & 7 deletions src/lib.rs → canvas/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
//! Pure-Rust 2-D drawing library with a web-canvas-like API.
//!
//! No external dependencies are required.
//! No external dependencies are required. All drawing operations work on an
//! in-memory RGBA pixel buffer. To encode or decode PNG images, use the
//! companion `images` crate.
//!
//! # Quick start
//!
//! ```
//! use canvas_rs::Canvas;
//! use canvas::Canvas;
//!
//! // Create a 200×100 canvas.
//! let canvas = Canvas::new(200, 100);
Expand All @@ -20,17 +22,12 @@
//! ctx.begin_path();
//! ctx.arc(100.0, 50.0, 40.0, 0.0, std::f64::consts::PI * 2.0, false);
//! ctx.fill();
//!
//! // Export as data URL.
//! let url = canvas.to_data_url();
//! assert!(url.starts_with("data:image/png;base64,"));
//! ```

pub mod canvas;
pub mod color;
pub mod image;
pub mod path;
pub mod png;
pub mod render;

pub use canvas::{Canvas, Context2D};
Expand Down
8 changes: 4 additions & 4 deletions src/path.rs → canvas/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ impl Path {
}
current.clear();
// pen stays at the start of the closed sub-path (web spec)
if let Some(sp) = sub_paths.last()
&& let Some(&p) = sp.first()
{
pen = p;
if let Some(sp) = sub_paths.last() {
if let Some(&p) = sp.first() {
pen = p;
}
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/render.rs → canvas/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ pub fn put_pixel(
return;
}
let idx = (y as u32 * width + x as u32) as usize;
if let Some(mask) = clip
&& !mask[idx]
{
return;
if let Some(mask) = clip {
if !mask[idx] {
return;
}
}
let base = idx * 4;
let dst = Color::rgba(buf[base], buf[base + 1], buf[base + 2], buf[base + 3]);
Expand Down
8 changes: 8 additions & 0 deletions images/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "images"
version = "0.1.0"
edition = "2021"

[dependencies]
canvas = { path = "../canvas" }
png = "0.17"
2 changes: 1 addition & 1 deletion src/png.rs → images/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ const B64_ALPHABET: &[u8] =

/// Encode `data` to standard base-64 (with `=` padding).
pub fn base64_encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
let mut chunks = data.chunks_exact(3);
for chunk in chunks.by_ref() {
let n = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
Expand Down
75 changes: 75 additions & 0 deletions images/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! PNG encoding and decoding for the `canvas` crate.
//!
//! This crate wraps the core `canvas` RGBA buffer with PNG import/export
//! capabilities.
//!
//! # Quick start
//!
//! ```no_run
//! use canvas::Canvas;
//!
//! let mut canvas = Canvas::new(200, 100);
//! let mut ctx = canvas.get_context("2d").unwrap();
//! ctx.set_fill_style("red");
//! ctx.fill_rect(0.0, 0.0, 200.0, 100.0);
//!
//! // Export to a data URL.
//! let url = images::to_data_url(&canvas);
//! assert!(url.starts_with("data:image/png;base64,"));
//!
//! // Or get raw PNG bytes.
//! let png_bytes: Vec<u8> = images::to_blob(&canvas);
//! ```

pub mod encoder;

pub use encoder::{base64_encode, encode_png};

use canvas::{Canvas, ImageData};

/// Encode a `Canvas` as raw PNG bytes.
pub fn to_blob(canvas: &Canvas) -> Vec<u8> {
let buf = canvas.pixels();
encode_png(canvas.width(), canvas.height(), &buf)
}

/// Encode a `Canvas` as a `data:image/png;base64,...` URL.
pub fn to_data_url(canvas: &Canvas) -> String {
format!("data:image/png;base64,{}", base64_encode(&to_blob(canvas)))
}

/// Decode a PNG byte slice into an [`ImageData`] with RGBA pixels.
///
/// Returns an error string if the bytes cannot be decoded as a valid PNG.
pub fn from_png(bytes: &[u8]) -> Result<ImageData, String> {
use png::ColorType;
use std::io::Cursor;

let decoder = png::Decoder::new(Cursor::new(bytes));
let mut reader = decoder
.read_info()
.map_err(|e| format!("PNG read_info error: {e}"))?;
let mut buf = vec![0u8; reader.output_buffer_size()];
let frame = reader
.next_frame(&mut buf)
.map_err(|e| format!("PNG decode error: {e}"))?;
let raw = buf[..frame.buffer_size()].to_vec();
let (w, h) = (frame.width, frame.height);
let rgba = match frame.color_type {
ColorType::Rgba => raw,
ColorType::Rgb => raw
.chunks(3)
.flat_map(|p| [p[0], p[1], p[2], 255u8])
.collect(),
ColorType::Grayscale => raw
.iter()
.flat_map(|&v| [v, v, v, 255u8])
.collect(),
ColorType::GrayscaleAlpha => raw
.chunks(2)
.flat_map(|p| [p[0], p[0], p[0], p[1]])
.collect(),
other => return Err(format!("unsupported PNG color type: {other:?}")),
};
Ok(ImageData::from_rgba(w, h, rgba))
}
Binary file added images/tests/image_220x200.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading