# core/canvas2d (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/canvas2d/

2D drawing target. (in place of the browser canvas that the original and games use through document.createElement("canvas") and getContext("2d"))
- The original engine bakes text, shading and shadows onto offscreen canvases (getBakeCanvas and getAtlasCanvas return those canvases),
  and games create their own canvases, draw paths, gradients, shadows, clips, images and text, then hand them to the engine as images. (glossy UI shells, logo atlases, sprite cropping, pixel measuring)
- In the Rust version, a single Canvas2D is both the canvas and its 2D context. Function names are the CanvasRenderingContext2D names converted to Rust conventions.
  (fillRect → fill_rect, fillStyle = → set_fill_style, getImageData → get_image_data) The same goes for Path2D, CanvasGradient, CanvasPattern and ImageData.
  What is drawn is turned into an engine Image with to_image and used in places such as Graphic and UIImageView. (returns the same Image if nothing changed)
- On the web, it draws directly to a browser canvas (a canvas element not attached to the document) and its 2D context, as in the original.
- Desktop has no browser, so the engine does the same work. It paints with tiny-skia, a Rust port of the Skia CPU rasterizer that Chrome uses.
  (the same version resvg already uses, no extra crates to download) Path points are transformed by the transform at the time they are added, as in the original, and gradients and patterns follow the transform at paint time.
  Path arc, ellipse, arcTo and roundRect store the same conic curves as Chrome, using the math of Blink canvas_path.cc and Skia SkPathBuilder,
  and at paint time they are split into quadratic curves within 0.25 device pixels, like the Skia CPU raster. (SkAutoConicToQuads, the old chop version Chrome uses)
  An engine Image whose CPU pixels were released on GPU upload is drawn by reading back its texture. (same as when Chrome draws a GPU-resident image onto a CPU canvas)
  Shadows paint the shape separately, blur it (sigma = shadowBlur / 2, three box blurs) and lay it down offset by shadowOffset, which is not transformed.
  copy, source-in, source-out, destination-in and destination-atop also clear outside the shape, as in the original. (the shape is painted separately and composited over the whole clipped region)
  Text is painted from coverage taken from the engine glyph cache (the same face selection, shaping, fallback fonts and color emoji as the Text component).
- Differences from the original:
  - Properties are setters and getters. Colors are CanvasStyle, which takes a Color or CSS color string, a gradient or a pattern.
  - roundRect radii are a list of numbers (f32) or elliptical corners ((x, y), CanvasRadius::Elliptical, the original DOMPointInit).
  - Desktop pixels use the same Skia math as Chrome but not the same version, so edge antialiasing and blur may differ slightly.

Example: Fill a circle and get it as an engine image

```rust
use vanilla::{Canvas2D, CanvasFillRule};

let mut canvas = Canvas2D::new(64, 64);
canvas.set_fill_style("#ff0000");
canvas.begin_path();
canvas.arc(32.0, 32.0, 24.0, 0.0, std::f64::consts::PI * 2.0, false);
canvas.fill(CanvasFillRule::NonZero);
assert_eq!(canvas.get_image_data(32, 32, 1, 1).data, vec![255, 0, 0, 255]);
assert_eq!(canvas.get_image_data(2, 2, 1, 1).data, vec![0, 0, 0, 0]);

let image = canvas.to_image();
assert_eq!((image.get_width(), image.get_height()), (64, 64));
```

## CanvasMatrix (struct) (Clone, Copy, Debug, PartialEq, Default)

2D transform matrix. (a, b, c, d, e, f of the original DOMMatrix. x' = a x + c y + e, y' = b x + d y + f)

Example: A matrix that scales by two then translates, and its inverse

```rust
use vanilla::CanvasMatrix;

let translate = CanvasMatrix::create(1.0, 0.0, 0.0, 1.0, 10.0, 20.0);
let scale = CanvasMatrix::create(2.0, 0.0, 0.0, 2.0, 0.0, 0.0);
let matrix = translate.multiply(&scale);
assert_eq!(matrix.transform_point(1.0, 1.0), (12.0, 22.0));

let inverse = matrix.invert().unwrap();
assert_eq!(inverse.transform_point(12.0, 22.0), (1.0, 1.0));
assert!(CanvasMatrix::create(0.0, 0.0, 0.0, 0.0, 0.0, 0.0).invert().is_none());
assert_eq!(CanvasMatrix::default(), CanvasMatrix::IDENTITY);
```

- `pub a: f32` (field, since 0.4.0): Horizontal scale. (multiplied by x and added to the new x)
  - returns f32
- `pub b: f32` (field, since 0.4.0): Vertical skew. (multiplied by x and added to the new y)
  - returns f32
- `pub c: f32` (field, since 0.4.0): Horizontal skew. (multiplied by y and added to the new x)
  - returns f32
- `pub d: f32` (field, since 0.4.0): Vertical scale. (multiplied by y and added to the new y)
  - returns f32
- `pub e: f32` (field, since 0.4.0): Horizontal translation. (pixels)
  - returns f32
- `pub f: f32` (field, since 0.4.0): Vertical translation. (pixels)
  - returns f32
- `pub const IDENTITY: CanvasMatrix` (static, since 0.4.0): Identity matrix.
  - returns CanvasMatrix
- `pub fn create(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> CanvasMatrix` (static, since 0.4.0): Creates from six values.
  - `a` f64: Horizontal scale. (multiplied by x and added to the new x)
  - `b` f64: Vertical skew. (multiplied by x and added to the new y)
  - `c` f64: Horizontal skew. (multiplied by y and added to the new x)
  - `d` f64: Vertical scale. (multiplied by y and added to the new y)
  - `e` f64: Horizontal translation. (pixels)
  - `f` f64: Vertical translation. (pixels)
  - returns CanvasMatrix: The matrix of those six values.
- `pub fn multiply(&self, other: &CanvasMatrix) -> CanvasMatrix` (method, since 0.4.0): Multiplies on the right. (self × other, other is applied first. The math of the original transform)
  - `other` &CanvasMatrix: Matrix to multiply on the right. (applied to points first)
  - returns CanvasMatrix: The self × other matrix.
- `pub fn transform_point(&self, x: f64, y: f64) -> (f64, f64)` (method, since 0.4.0): Transforms a point.
  - `x` f64: Point x.
  - `y` f64: Point y.
  - returns (f64, f64): The transformed point (x', y'). (computed with the elements widened to f64, double like the original DOMMatrix.transformPoint)
- `pub fn invert(&self) -> Option<CanvasMatrix>` (method, since 0.4.0): Inverse matrix. (None if not invertible)
  - returns Option<CanvasMatrix>: The inverse matrix. None if it cannot be inverted because the determinant is 0 or not finite.
- `pub fn is_finite(&self) -> bool` (method, since 0.4.0): Whether all values are finite.
  - returns bool: true if all six values are finite.

## Path2D (struct) (Clone, Debug, Default, PartialEq)

Path. (the original Path2D, the canvas's current path is also this)
- Points of the adding functions are transformed by matrix and stored. Path2D uses the identity matrix, and the canvas's current path uses the transform at the time of adding. (same as the original)
- arc, ellipse, arcTo and roundRect port the math of Blink canvas_path.cc and Skia SkPathBuilder to store the same conic curve points and weights.
  (conic curves keep the same weights through affine transforms, so the transformed points are also the same) At paint time they are split into quadratic curves within 0.25 device pixels, like the Skia CPU raster.

Example: A rectangle with a hollow center using the even-odd rule

```rust
use vanilla::{Canvas2D, CanvasFillRule, Path2D};

let mut ring = Path2D::new();
ring.rect(0.0, 0.0, 40.0, 40.0);
ring.rect(10.0, 10.0, 20.0, 20.0);
assert!(!ring.is_empty());

let mut canvas = Canvas2D::new(40, 40);
canvas.fill_path(&ring, CanvasFillRule::EvenOdd);
assert_eq!(canvas.get_image_data(5, 5, 1, 1).data[3], 255);
assert_eq!(canvas.get_image_data(20, 20, 1, 1).data[3], 0);
assert!(!canvas.is_point_in_path2d(&ring, 20.0, 20.0, CanvasFillRule::EvenOdd));
assert!(canvas.is_point_in_path2d(&ring, 20.0, 20.0, CanvasFillRule::NonZero));
```

- `pub fn new() -> Path2D` (constructor, since 0.4.0): Empty path.
  - returns Path2D: A Path2D with no subpaths.
- `pub fn is_empty(&self) -> bool` (method, since 0.4.0): Whether it is empty.
  - returns bool: true if there are no subpaths at all.
- `pub fn move_to(&mut self, x: f64, y: f64)` (method, since 0.4.0): New subpath. (the original moveTo)
  - `x` f64: Start point x of the new subpath.
  - `y` f64: Start point y of the new subpath.
- `pub fn line_to(&mut self, x: f64, y: f64)` (method, since 0.4.0): Straight line. (the original lineTo, starts a subpath at that point if there is none)
  - `x` f64: End point x.
  - `y` f64: End point y.
- `pub fn quadratic_curve_to(&mut self, control_x: f64, control_y: f64, x: f64, y: f64)` (method, since 0.4.0): Quadratic curve. (the original quadraticCurveTo)
  - `control_x` f64: Control point x.
  - `control_y` f64: Control point y.
  - `x` f64: End point x.
  - `y` f64: End point y.
- `pub fn bezier_curve_to(&mut self, first_control_x: f64, first_control_y: f64, second_control_x: f64, second_control_y: f64, x: f64, y: f64)` (method, since 0.4.0): Cubic curve. (the original bezierCurveTo)
  - `first_control_x` f64: First control point x.
  - `first_control_y` f64: First control point y.
  - `second_control_x` f64: Second control point x.
  - `second_control_y` f64: Second control point y.
  - `x` f64: End point x.
  - `y` f64: End point y.
- `pub fn arc(&mut self, x: f64, y: f64, radius: f64, start_angle: f64, end_angle: f64, is_counterclockwise: bool) -> bool` (method, since 0.4.0): Arc. (the original arc, does nothing and returns false if the radius is negative, like the original's exception)
  - `x` f64: Center x.
  - `y` f64: Center y.
  - `radius` f64: Radius. (false if negative)
  - `start_angle` f64: Start angle. (radians, 0 is to the right, clockwise on screen is +)
  - `end_angle` f64: End angle. (radians)
  - `is_counterclockwise` bool: true to go counterclockwise.
  - returns bool: false if the radius is negative (where the original throws), otherwise true. (if any value is non-finite, adds nothing and returns true like the original)
- `pub fn arc_to(&mut self, first_x: f64, first_y: f64, second_x: f64, second_y: f64, radius: f64) -> bool` (method, since 0.4.0): Arc between two tangents. (the original arcTo, false if the radius is negative)
  - `first_x` f64: x of the point where the two tangents meet. (the first tangent runs from the current point to this point)
  - `first_y` f64: y of the point where the two tangents meet.
  - `second_x` f64: x of a point the second tangent passes through. (the second tangent runs from the meeting point to this point)
  - `second_y` f64: y of a point the second tangent passes through.
  - `radius` f64: Radius. (false if negative)
  - returns bool: false if the radius is negative (where the original throws), otherwise true. (if any value is non-finite, adds nothing and returns true like the original)
- `pub fn ellipse(&mut self, x: f64, y: f64, radius_x: f64, radius_y: f64, rotation: f64, start_angle: f64, end_angle: f64, is_counterclockwise: bool) -> bool` (method, since 0.4.0): Elliptical arc. (the original ellipse, false if a radius is negative)
  - `x` f64: Center x.
  - `y` f64: Center y.
  - `radius_x` f64: Horizontal radius. (before rotation, false if negative)
  - `radius_y` f64: Vertical radius. (before rotation, false if negative)
  - `rotation` f64: Angle to rotate the ellipse. (radians, clockwise on screen is +)
  - `start_angle` f64: Start angle. (radians, 0 is to the right in the ellipse coordinate system)
  - `end_angle` f64: End angle. (radians)
  - `is_counterclockwise` bool: true to go counterclockwise.
  - returns bool: false if the radius is negative (where the original throws), otherwise true. (if any value is non-finite, adds nothing and returns true like the original)
- `pub fn rect(&mut self, x: f64, y: f64, width: f64, height: f64)` (method, since 0.4.0): Rectangle. (the original rect, adds a closed subpath and starts a new subpath at (x, y))
  - `x` f64: Top-left x.
  - `y` f64: Top-left y.
  - `width` f64: Width. (leftward from x if negative)
  - `height` f64: Height. (upward from y if negative)
- `pub fn round_rect<R: Into<CanvasRadius> + Copy>(&mut self, x: f32, y: f32, width: f32, height: f32, radius_list: &[R]) -> bool` (method, since 0.4.0): Rounded rectangle. (the original roundRect, 1 ~ 4 radii. Takes numbers (f32) or elliptical corners ((x, y), CanvasRadius::Elliptical). false if invalid)
  - `x` f32: Top-left x.
  - `y` f32: Top-left y.
  - `width` f32: Width. (leftward from x if negative)
  - `height` f32: Height. (upward from y if negative)
  - `radius_list` &[R]: Corner radii, 1 ~ 4 of them. (as in the original: 1 for all four corners, 2 for top-left and bottom-right / top-right and bottom-left, 3 for top-left / top-right and bottom-left / bottom-right, 4 for top-left, top-right, bottom-right, bottom-left)
  - returns bool: false if there are not 1 ~ 4 radii or a radius is negative (where the original throws), otherwise true.
- `pub fn close_path(&mut self)` (method, since 0.4.0): Closes the subpath. (the original closePath)
- `pub fn add_path(&mut self, path: &Path2D, transform: Option<CanvasMatrix>)` (method, since 0.4.0): Adds another path. (the original addPath, transforms it by the given transform before adding)
  - `path` &Path2D: Path to add.
  - `transform` Option<CanvasMatrix>: Transform to apply before adding. (as is if None, adds nothing if any value is non-finite)

## CanvasGradient (struct) (Clone, Debug, PartialEq)

Gradient. (the original CanvasGradient)

Example: A horizontal gradient from black to white

```rust
use vanilla::{Canvas2D, CanvasGradientKind};

let mut canvas = Canvas2D::new(100, 10);
let mut gradient = canvas.create_linear_gradient(0.0, 0.0, 100.0, 0.0);
assert!(gradient.add_color_stop(0.0, "#000000"));
assert!(gradient.add_color_stop(1.0, "#ffffff"));
assert!(!gradient.add_color_stop(1.5, "#ff0000"));
assert_eq!(gradient.get_color_stops().len(), 2);
assert!(matches!(gradient.get_kind(), CanvasGradientKind::Linear { .. }));

canvas.set_fill_style(&gradient);
canvas.fill_rect(0.0, 0.0, 100.0, 10.0);
assert!(canvas.get_image_data(1, 5, 1, 1).data[0] < 10);
assert!(canvas.get_image_data(98, 5, 1, 1).data[0] > 245);
```

- `pub fn add_color_stop(&mut self, offset: f64, color: impl Into<Color>) -> bool` (method, since 0.4.0): Adds a color stop. (the original addColorStop, if the offset is outside 0 ~ 1 it is not added and returns false, like the original's exception. Equal offsets keep the order they were added)
  - `offset` f64: Offset. (0 ~ 1, false if outside)
  - `color` impl Into<Color>: Color. (Color or CSS color text)
  - returns bool: true if added. false if the offset is outside 0 ~ 1.
- `pub fn get_kind(&self) -> CanvasGradientKind` (method, since 0.4.0): Kind.
  - returns CanvasGradientKind: The kind and coordinates given at creation.
- `pub fn get_color_stops(&self) -> &[(f32, Color)]` (method, since 0.4.0): Color stop list. (in offset order)
  - returns &[(f32, Color)]: (offset, color) list. (in offset order, equal offsets in the order they were added)

## CanvasPattern (struct) (Clone, Debug, PartialEq)

Pattern. (the original CanvasPattern, holds the image at creation time as premultiplied RGBA)

Example: Fill by repeating red and blue pixels horizontally and vertically

```rust
use vanilla::{Canvas2D, CanvasPatternRepetition};

let mut tile = Canvas2D::new(2, 1);
tile.set_fill_style("#ff0000");
tile.fill_rect(0.0, 0.0, 1.0, 1.0);
tile.set_fill_style("#0000ff");
tile.fill_rect(1.0, 0.0, 1.0, 1.0);

let mut canvas = Canvas2D::new(6, 1);
let pattern = canvas.create_pattern(&tile, CanvasPatternRepetition::Repeat).unwrap();
assert_eq!(pattern.get_repetition(), CanvasPatternRepetition::Repeat);
canvas.set_fill_style(pattern);
canvas.fill_rect(0.0, 0.0, 6.0, 1.0);
assert_eq!(canvas.get_image_data(2, 0, 1, 1).data, vec![255, 0, 0, 255]);
assert_eq!(canvas.get_image_data(5, 0, 1, 1).data, vec![0, 0, 255, 255]);
```

- `pub fn set_transform(&mut self, transform: CanvasMatrix)` (method, since 0.4.0): Sets the pattern transform. (the original setTransform)
  - `transform` CanvasMatrix: Pattern transform. (pattern image coordinates → coordinates at paint time, ignored if any value is non-finite)
- `pub fn get_repetition(&self) -> CanvasPatternRepetition` (method, since 0.4.0): Repetition.
  - returns CanvasPatternRepetition: The repetition given at creation.

## ImageData (struct) (Clone, Debug, PartialEq, Eq)

Pixel data. (the original ImageData, non-premultiplied RGBA)

Example: Write two pixels to a canvas and read them back

```rust
use vanilla::{Canvas2D, ImageData};

let mut image_data = ImageData::new(2, 1);
assert_eq!(image_data.data, vec![0; 8]);
image_data.data.copy_from_slice(&[255, 0, 0, 255, 0, 0, 255, 255]);

let mut canvas = Canvas2D::new(4, 4);
canvas.put_image_data(&image_data, 1, 1);
assert_eq!(canvas.get_image_data(1, 1, 2, 1), image_data);
```

- `pub width: u32` (field, since 0.4.0): Width. (pixels)
  - returns u32
- `pub height: u32` (field, since 0.4.0): Height. (pixels)
  - returns u32
- `pub data: Vec<u8>` (field, since 0.4.0): Pixels. (row by row from left to right, R, G, B, A bytes per pixel, width x height x 4 of them)
  - returns Vec<u8>
- `pub fn new(width: u32, height: u32) -> ImageData` (constructor, since 0.4.0): Pixel data filled with transparent black. (the original createImageData, new ImageData(w, h))
  - `width` u32: Width. (pixels)
  - `height` u32: Height. (pixels)
  - returns ImageData: Pixel data with every byte 0.

## CanvasRadius (enum) (Clone, Copy, Debug, PartialEq, From<f64>, From<(f64, f64)>)

Rounded rectangle corner radius. (a number or DOMPointInit {x, y} in the original roundRect)

- `Circular` = `Circular(f32)`: A radius equal horizontally and vertically. (a number in the original)
- `Elliptical` = `Elliptical{ x: f32, y: f32, }`: Horizontal x and vertical y radii. (the original DOMPointInit {x, y})

## CanvasGradientKind (enum) (Clone, Copy, Debug, PartialEq)

Gradient kind.

- `Linear` = `Linear{ start_x: f32, start_y: f32, end_x: f32, end_y: f32, }`: The original createLinearGradient(x0, y0, x1, y1)
- `Radial` = `Radial{ start_x: f32, start_y: f32, start_radius: f32, end_x: f32, end_y: f32, end_radius: f32, }`: The original createRadialGradient(x0, y0, r0, x1, y1, r1)
- `Conic` = `Conic{ start_angle: f32, center_x: f32, center_y: f32, }`: The original createConicGradient(startAngle, x, y)

## CanvasPatternRepetition (enum) (Clone, Copy, Debug, PartialEq, Eq)

Pattern repetition. (the original "repeat", "repeat-x", "repeat-y", "no-repeat")

- `Repeat`: Repeats horizontally and vertically. (the original "repeat")
- `RepeatX`: Repeats only horizontally. (the original "repeat-x")
- `RepeatY`: Repeats only vertically. (the original "repeat-y")
- `NoRepeat`: A single copy. (the original "no-repeat")

- `pub fn get_name(&self) -> &'static str` (method, since 0.4.0): Original text.
  - returns &'static str: One of "repeat", "repeat-x", "repeat-y", "no-repeat".

## CanvasStyle (enum) (Clone, Debug, PartialEq, From<Color>, From<&str>, From<&String>, From<CanvasGradient>, From<&CanvasGradient>, From<CanvasPattern>, From<&CanvasPattern>)

Paint. (the original fillStyle, strokeStyle color text, CanvasGradient, CanvasPattern)

- `Color` = `Color(Color)`: Solid color.
- `Gradient` = `Gradient(CanvasGradient)`: Gradient.
- `Pattern` = `Pattern(CanvasPattern)`: Pattern.

## CanvasFillRule (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Fill rule. (the original "nonzero", "evenodd")

- `NonZero`: Inside if the winding number is not 0. (the original "nonzero", default)
- `EvenOdd`: Inside if the crossing count is odd. (the original "evenodd")

## CanvasLineCap (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Line cap. (the original lineCap)

- `Butt`: Cut off at the end. (the original "butt", default)
- `Round`: Adds a half circle. (the original "round")
- `Square`: Adds a square extending half the line width. (the original "square")

## CanvasLineJoin (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Line join. (the original lineJoin)

- `Miter`: Extends to a sharp point. (the original "miter", default, beveled like Bevel when the miter limit is exceeded)
- `Round`: Joins with a round. (the original "round")
- `Bevel`: Cuts off the corner. (the original "bevel")

## CanvasTextAlign (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Horizontal text alignment. (the original textAlign, start and end are treated as left-to-right text)

- `Start`: The text starts at x. (the original "start", default)
- `End`: The text ends at x. (the original "end")
- `Left`: x is the left edge of the text. (the original "left")
- `Right`: x is the right edge of the text. (the original "right")
- `Center`: x is the center of the text. (the original "center")

## CanvasTextBaseline (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Text baseline. (the original textBaseline)

- `Top`: y is the top of the em box. (the original "top")
- `Hanging`: y is the hanging baseline. (the original "hanging", the top baseline of scripts like Devanagari)
- `Middle`: y is the middle of the em box. (the original "middle")
- `Alphabetic`: y is the alphabetic baseline. (the original "alphabetic", default)
- `Ideographic`: y is the ideographic baseline. (the original "ideographic")
- `Bottom`: y is the bottom of the em box. (the original "bottom")

## CanvasImageSource (enum) (Clone, Copy, From<&'a crate::core::image::Image>, From<&'a std::rc::Rc<crate::core::image::Image>>, From<&'a Canvas2D>)

Image to draw. (the images the original drawImage and createPattern take: engine Image, another canvas)

- `Image` = `Image(&'a crate::core::image::Image)`: Engine image. (if its CPU pixels were released when uploaded to the GPU, they are read back from the texture)
- `Canvas` = `Canvas(&'a Canvas2D)`: Another canvas.

- `pub fn get_size(&self) -> (u32, u32)` (method, since 0.4.0): Size.
  - returns (u32, u32): (width, height). (pixels)
