vanilladocs
vanillapunch.com
API / core/canvas2d

core/canvas2d

2D 그리기 대상. (원본과 게임이 document.createElement("canvas") 와 getContext("2d") 로 쓰는 브라우저 캔버스 자리)

  • 원본 엔진은 글, 그늘, 그림자를 떨어진 캔버스에 굽고(getBakeCanvas, getAtlasCanvas 가 그 캔버스를 돌려준다), 게임은 제 캔버스를 만들어 경로, 그라데이션, 그림자, 자르기, 그림, 글을 그린 뒤 엔진에 그림으로 넘긴다. (윤 나는 UI 껍데기, 로고 아틀라스, 스프라이트 자르기, 픽셀 재기)
  • 러스트 판은 Canvas2D 하나가 캔버스와 그 2D 컨텍스트다. 함수 이름은 CanvasRenderingContext2D 의 이름을 러스트 규칙으로 바꾼 것이다. (fillRect → fill_rect, fillStyle = → set_fill_style, getImageData → get_image_data) Path2D, CanvasGradient, CanvasPattern, ImageData 도 같다. 그린 것은 to_image 로 엔진 Image 를 받아 Graphic, UIImageView 같은 곳에 쓴다. (바뀌지 않았으면 같은 Image 를 돌려준다)
  • 웹은 원본처럼 브라우저 캔버스(문서에 붙이지 않은 canvas 요소)와 그 2D 컨텍스트에 그대로 그린다.
  • 데스크탑은 브라우저가 없어 엔진이 같은 일을 한다. 크롬이 쓰는 Skia 의 CPU 래스터라이저를 러스트로 옮긴 tiny-skia 로 칠한다. (resvg 가 이미 쓰는 같은 판, 더 받는 크레이트가 없다) 경로 점은 원본처럼 더할 때의 변환으로 옮기고, 그라데이션과 패턴은 칠할 때의 변환을 따른다. 경로의 arc, ellipse, arcTo, roundRect 는 크롬처럼 블링크 canvas_path.cc 와 스키아 SkPathBuilder 의 셈으로 같은 원뿔 곡선을 담고, 칠할 때 스키아 CPU 래스터처럼 기기 픽셀 0.25 안의 2 차 곡선으로 나눈다. (SkAutoConicToQuads, 크롬이 쓰는 옛 판 chop) GPU 에 올리며 CPU 픽셀을 놓은 엔진 Image 는 그 텍스처를 되읽어 그린다. (크롬이 GPU 에 있는 그림을 CPU 캔버스에 그릴 때와 같다) 그림자는 모양을 따로 칠해 흐리고(시그마 = shadowBlur / 2, 상자 흐림 세 번) 변환을 받지 않는 shadowOffset 만큼 옮겨 깐다. copy, source-in, source-out, destination-in, destination-atop 은 원본처럼 모양 밖도 지운다. (모양을 따로 칠해 자른 영역 전체에 합친다) 글은 엔진 글자 캐시(Text 컴포넌트와 같은 얼굴 고르기, 모양 짓기, 대체 글꼴, 색 이모지)로 덮인 정도를 받아 칠한다.
  • 원본과 다른 점:
  • 속성은 setter 와 getter 다. 색은 Color 나 CSS 색 글, 그라데이션, 패턴을 받는 CanvasStyle 이다.
  • roundRect 의 반지름은 수(f32)나 타원 모서리((x, y), CanvasRadius::Elliptical, 원본 DOMPointInit)의 목록이다.
  • 데스크탑 픽셀은 크롬과 같은 Skia 셈이지만 같은 판이 아니라 가장자리 안티에일리어싱과 흐림이 조금 다를 수 있다.

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
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));

CanvasMatrixstruct traits Clone, Copy, Debug, PartialEq, Default

소스source

2D 변환 행렬. (원본 DOMMatrix 의 a, b, c, d, e, f. x' = a x + c y + e, y' = b x + d y + f)

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
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);
정적staticpub const IDENTITY: CanvasMatrix#0.4.0 부터since 0.4.0소스source

단위 행렬.

Identity matrix.

반환ReturnsCanvasMatrix

정적staticpub fn create(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> CanvasMatrix#0.4.0 부터since 0.4.0소스source

여섯 값으로 만들기.

Creates from six values.

af64
가로 배율. (x 에 곱해 새 x 에 더한다)Horizontal scale. (multiplied by x and added to the new x)
bf64
세로 기울임. (x 에 곱해 새 y 에 더한다)Vertical skew. (multiplied by x and added to the new y)
cf64
가로 기울임. (y 에 곱해 새 x 에 더한다)Horizontal skew. (multiplied by y and added to the new x)
df64
세로 배율. (y 에 곱해 새 y 에 더한다)Vertical scale. (multiplied by y and added to the new y)
ef64
가로 이동. (픽셀)Horizontal translation. (pixels)
ff64
세로 이동. (픽셀)Vertical translation. (pixels)

반환ReturnsCanvasMatrix 그 여섯 값의 행렬.The matrix of those six values.

필드fieldpub a: f32#0.4.0 부터since 0.4.0소스source

가로 배율. (x 에 곱해 새 x 에 더한다)

Horizontal scale. (multiplied by x and added to the new x)

반환Returnsf32

필드fieldpub b: f32#0.4.0 부터since 0.4.0소스source

세로 기울임. (x 에 곱해 새 y 에 더한다)

Vertical skew. (multiplied by x and added to the new y)

반환Returnsf32

필드fieldpub c: f32#0.4.0 부터since 0.4.0소스source

가로 기울임. (y 에 곱해 새 x 에 더한다)

Horizontal skew. (multiplied by y and added to the new x)

반환Returnsf32

필드fieldpub d: f32#0.4.0 부터since 0.4.0소스source

세로 배율. (y 에 곱해 새 y 에 더한다)

Vertical scale. (multiplied by y and added to the new y)

반환Returnsf32

필드fieldpub e: f32#0.4.0 부터since 0.4.0소스source

가로 이동. (픽셀)

Horizontal translation. (pixels)

반환Returnsf32

필드fieldpub f: f32#0.4.0 부터since 0.4.0소스source

세로 이동. (픽셀)

Vertical translation. (pixels)

반환Returnsf32

메서드methodpub fn multiply(&self, other: &CanvasMatrix) -> CanvasMatrix#0.4.0 부터since 0.4.0소스source

뒤에 곱하기. (self × other, other 를 먼저 적용한다. 원본 transform 의 셈)

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)

반환ReturnsCanvasMatrix self × other 행렬.The self × other matrix.

메서드methodpub fn transform_point(&self, x: f64, y: f64) -> (f64, f64)#0.4.0 부터since 0.4.0소스source

점 옮기기.

Transforms a point.

xf64
점 x.Point x.
yf64
점 y.Point y.

반환Returns(f64, f64) 옮긴 점 (x', y'). (칸을 f64 로 넓혀 셈한다, 원본 DOMMatrix.transformPoint 처럼 double)The transformed point (x', y'). (computed with the elements widened to f64, double like the original DOMMatrix.transformPoint)

메서드methodpub fn invert(&self) -> Option<CanvasMatrix>#0.4.0 부터since 0.4.0소스source

역행렬. (뒤집을 수 없으면 None)

Inverse matrix. (None if not invertible)

반환ReturnsOption<CanvasMatrix> 역행렬. 행렬식이 0 이거나 유한하지 않아 뒤집을 수 없으면 None.The inverse matrix. None if it cannot be inverted because the determinant is 0 or not finite.

메서드methodpub fn is_finite(&self) -> bool#0.4.0 부터since 0.4.0소스source

모든 값이 유한한지.

Whether all values are finite.

반환Returnsbool 여섯 값이 모두 유한하면 true.true if all six values are finite.

Path2Dstruct traits Clone, Debug, Default, PartialEq

소스source

경로. (원본 Path2D, 캔버스의 지금 경로도 이것이다)

  • 더하는 함수의 점은 matrix 로 옮겨 담는다. Path2D 는 단위 행렬이고, 캔버스의 지금 경로는 더할 때의 변환이다. (원본과 같다)
  • arc, ellipse, arcTo, roundRect 는 블링크 canvas_path.cc 와 스키아 SkPathBuilder 의 셈을 옮겨 같은 원뿔 곡선 점과 무게를 담는다. (원뿔 곡선은 아핀 변환을 지나도 무게가 같아 옮겨 담은 점도 같다) 칠할 때는 스키아 CPU 래스터처럼 기기 픽셀 0.25 안의 2 차 곡선으로 나눈다.

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
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));
생성자constructorpub fn new() -> Path2D#0.4.0 부터since 0.4.0소스source

빈 경로.

Empty path.

반환ReturnsPath2D 조각이 없는 Path2D.A Path2D with no subpaths.

메서드methodpub fn is_empty(&self) -> bool#0.4.0 부터since 0.4.0소스source

비었는지.

Whether it is empty.

반환Returnsbool 조각이 하나도 없으면 true.true if there are no subpaths at all.

메서드methodpub fn move_to(&mut self, x: f64, y: f64)#0.4.0 부터since 0.4.0소스source

새 조각. (원본 moveTo)

New subpath. (the original moveTo)

xf64
새 조각의 시작 점 x.Start point x of the new subpath.
yf64
새 조각의 시작 점 y.Start point y of the new subpath.
메서드methodpub fn line_to(&mut self, x: f64, y: f64)#0.4.0 부터since 0.4.0소스source

곧은 선. (원본 lineTo, 조각이 없으면 그 점에서 조각을 시작한다)

Straight line. (the original lineTo, starts a subpath at that point if there is none)

xf64
끝 점 x.End point x.
yf64
끝 점 y.End point y.
메서드methodpub fn quadratic_curve_to(&mut self, control_x: f64, control_y: f64, x: f64, y: f64)#0.4.0 부터since 0.4.0소스source

2 차 곡선. (원본 quadraticCurveTo)

Quadratic curve. (the original quadraticCurveTo)

control_xf64
조정점 x.Control point x.
control_yf64
조정점 y.Control point y.
xf64
끝 점 x.End point x.
yf64
끝 점 y.End point y.
메서드methodpub 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)#0.4.0 부터since 0.4.0소스source

3 차 곡선. (원본 bezierCurveTo)

Cubic curve. (the original bezierCurveTo)

first_control_xf64
첫 조정점 x.First control point x.
first_control_yf64
첫 조정점 y.First control point y.
second_control_xf64
둘째 조정점 x.Second control point x.
second_control_yf64
둘째 조정점 y.Second control point y.
xf64
끝 점 x.End point x.
yf64
끝 점 y.End point y.
메서드methodpub fn arc(&mut self, x: f64, y: f64, radius: f64, start_angle: f64, end_angle: f64, is_counterclockwise: bool) -> bool#0.4.0 부터since 0.4.0소스source

원호. (원본 arc, 반지름이 음수면 원본의 예외처럼 아무것도 하지 않고 false)

Arc. (the original arc, does nothing and returns false if the radius is negative, like the original's exception)

xf64
가운데 x.Center x.
yf64
가운데 y.Center y.
radiusf64
반지름. (음수면 false)Radius. (false if negative)
start_anglef64
시작 각. (라디안, 0 이 오른쪽, 화면에서 시계 방향이 +)Start angle. (radians, 0 is to the right, clockwise on screen is +)
end_anglef64
끝 각. (라디안)End angle. (radians)
is_counterclockwisebool
true 면 반시계 방향으로 돈다.true to go counterclockwise.

반환Returnsbool 반지름이 음수면 false(원본의 예외 자리), 그 밖에는 true. (유한하지 않은 값이 있으면 원본처럼 아무것도 더하지 않고 true)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)

메서드methodpub fn arc_to(&mut self, first_x: f64, first_y: f64, second_x: f64, second_y: f64, radius: f64) -> bool#0.4.0 부터since 0.4.0소스source

두 접선 사이 원호. (원본 arcTo, 반지름이 음수면 false)

Arc between two tangents. (the original arcTo, false if the radius is negative)

first_xf64
두 접선이 만나는 점 x. (지금 점에서 이 점까지가 첫 접선)x of the point where the two tangents meet. (the first tangent runs from the current point to this point)
first_yf64
두 접선이 만나는 점 y.y of the point where the two tangents meet.
second_xf64
둘째 접선이 지나는 점 x. (만나는 점에서 이 점까지가 둘째 접선)x of a point the second tangent passes through. (the second tangent runs from the meeting point to this point)
second_yf64
둘째 접선이 지나는 점 y.y of a point the second tangent passes through.
radiusf64
반지름. (음수면 false)Radius. (false if negative)

반환Returnsbool 반지름이 음수면 false(원본의 예외 자리), 그 밖에는 true. (유한하지 않은 값이 있으면 원본처럼 아무것도 더하지 않고 true)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)

메서드methodpub 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#0.4.0 부터since 0.4.0소스source

타원호. (원본 ellipse, 반지름이 음수면 false)

Elliptical arc. (the original ellipse, false if a radius is negative)

xf64
가운데 x.Center x.
yf64
가운데 y.Center y.
radius_xf64
가로 반지름. (돌리기 전, 음수면 false)Horizontal radius. (before rotation, false if negative)
radius_yf64
세로 반지름. (돌리기 전, 음수면 false)Vertical radius. (before rotation, false if negative)
rotationf64
타원을 돌리는 각. (라디안, 화면에서 시계 방향이 +)Angle to rotate the ellipse. (radians, clockwise on screen is +)
start_anglef64
시작 각. (라디안, 타원 좌표계에서 0 이 오른쪽)Start angle. (radians, 0 is to the right in the ellipse coordinate system)
end_anglef64
끝 각. (라디안)End angle. (radians)
is_counterclockwisebool
true 면 반시계 방향으로 돈다.true to go counterclockwise.

반환Returnsbool 반지름이 음수면 false(원본의 예외 자리), 그 밖에는 true. (유한하지 않은 값이 있으면 원본처럼 아무것도 더하지 않고 true)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)

메서드methodpub fn rect(&mut self, x: f64, y: f64, width: f64, height: f64)#0.4.0 부터since 0.4.0소스source

사각형. (원본 rect, 닫힌 조각을 더하고 (x, y) 에서 새 조각)

Rectangle. (the original rect, adds a closed subpath and starts a new subpath at (x, y))

xf64
왼쪽 위 x.Top-left x.
yf64
왼쪽 위 y.Top-left y.
widthf64
폭. (음수면 x 에서 왼쪽으로)Width. (leftward from x if negative)
heightf64
높이. (음수면 y 에서 위로)Height. (upward from y if negative)
메서드methodpub fn round_rect<R: Into<CanvasRadius> + Copy>(&mut self, x: f32, y: f32, width: f32, height: f32, radius_list: &[R]) -> bool#0.4.0 부터since 0.4.0소스source

둥근 사각형. (원본 roundRect, 반지름 1 ~ 4 개. 수(f32)나 타원 모서리((x, y), CanvasRadius::Elliptical)를 받는다. 틀리면 false)

Rounded rectangle. (the original roundRect, 1 ~ 4 radii. Takes numbers (f32) or elliptical corners ((x, y), CanvasRadius::Elliptical). false if invalid)

xf32
왼쪽 위 x.Top-left x.
yf32
왼쪽 위 y.Top-left y.
widthf32
폭. (음수면 x 에서 왼쪽으로)Width. (leftward from x if negative)
heightf32
높이. (음수면 y 에서 위로)Height. (upward from y if negative)
radius_list&[R]
모서리 반지름 1 ~ 4 개. (원본처럼 1 개는 네 모서리, 2 개는 왼위와 오른아래 / 오른위와 왼아래, 3 개는 왼위 / 오른위와 왼아래 / 오른아래, 4 개는 왼위, 오른위, 오른아래, 왼아래)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)

반환Returnsbool 반지름이 1 ~ 4 개가 아니거나 음수 반지름이 있으면 false(원본의 예외 자리), 그 밖에는 true.false if there are not 1 ~ 4 radii or a radius is negative (where the original throws), otherwise true.

메서드methodpub fn close_path(&mut self)#0.4.0 부터since 0.4.0소스source

조각 닫기. (원본 closePath)

Closes the subpath. (the original closePath)

메서드methodpub fn add_path(&mut self, path: &Path2D, transform: Option<CanvasMatrix>)#0.4.0 부터since 0.4.0소스source

다른 경로 더하기. (원본 addPath, 변환을 주면 그 변환으로 옮겨 더한다)

Adds another path. (the original addPath, transforms it by the given transform before adding)

path&Path2D
더할 경로.Path to add.
transformOption<CanvasMatrix>
더하기 전에 옮길 변환. (None 이면 그대로, 유한하지 않은 값이 있으면 아무것도 더하지 않는다)Transform to apply before adding. (as is if None, adds nothing if any value is non-finite)

CanvasGradientstruct traits Clone, Debug, PartialEq

소스source

그라데이션. (원본 CanvasGradient)

Gradient. (the original CanvasGradient)

예제Example검정에서 흰색으로 가는 가로 그라데이션A horizontal gradient from black to white
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);
메서드methodpub fn add_color_stop(&mut self, offset: f64, color: impl Into<Color>) -> bool#0.4.0 부터since 0.4.0소스source

색 멈춤 더하기. (원본 addColorStop, 자리가 0 ~ 1 밖이면 원본의 예외처럼 더하지 않고 false. 같은 자리는 넣은 차례대로)

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)

offsetf64
자리. (0 ~ 1, 밖이면 false)Offset. (0 ~ 1, false if outside)
colorimpl Into<Color>
색. (Color 나 CSS 색 글)Color. (Color or CSS color text)

반환Returnsbool 더했으면 true. 자리가 0 ~ 1 밖이면 false.true if added. false if the offset is outside 0 ~ 1.

메서드methodpub fn get_kind(&self) -> CanvasGradientKind#0.4.0 부터since 0.4.0소스source

종류.

Kind.

반환ReturnsCanvasGradientKind 만들 때의 종류와 좌표.The kind and coordinates given at creation.

메서드methodpub fn get_color_stops(&self) -> &[(f32, Color)]#0.4.0 부터since 0.4.0소스source

색 멈춤 목록. (자리 차례)

Color stop list. (in offset order)

반환Returns&[(f32, Color)] (자리, 색) 목록. (자리 차례, 같은 자리는 넣은 차례)(offset, color) list. (in offset order, equal offsets in the order they were added)

CanvasPatternstruct traits Clone, Debug, PartialEq

소스source

패턴. (원본 CanvasPattern, 만들 때의 그림을 프리멀티플라이드 RGBA 로 든다)

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

예제Example빨강과 파랑 두 픽셀을 가로세로로 되풀이해 칠하기Fill by repeating red and blue pixels horizontally and vertically
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]);
메서드methodpub fn set_transform(&mut self, transform: CanvasMatrix)#0.4.0 부터since 0.4.0소스source

패턴 변환 설정. (원본 setTransform)

Sets the pattern transform. (the original setTransform)

transformCanvasMatrix
패턴 변환. (패턴 그림 좌표 → 칠할 때의 좌표, 유한하지 않은 값이 있으면 무시)Pattern transform. (pattern image coordinates → coordinates at paint time, ignored if any value is non-finite)
메서드methodpub fn get_repetition(&self) -> CanvasPatternRepetition#0.4.0 부터since 0.4.0소스source

되풀이.

Repetition.

반환ReturnsCanvasPatternRepetition 만들 때 준 되풀이.The repetition given at creation.

ImageDatastruct traits Clone, Debug, PartialEq, Eq

소스source

픽셀 묶음. (원본 ImageData, 프리멀티플라이하지 않은 RGBA)

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

예제Example두 픽셀을 캔버스에 쓰고 되읽기Write two pixels to a canvas and read them back
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);
생성자constructorpub fn new(width: u32, height: u32) -> ImageData#0.4.0 부터since 0.4.0소스source

투명한 검정으로 채운 픽셀 묶음. (원본 createImageData, new ImageData(w, h))

Pixel data filled with transparent black. (the original createImageData, new ImageData(w, h))

widthu32
폭. (픽셀)Width. (pixels)
heightu32
높이. (픽셀)Height. (pixels)

반환ReturnsImageData 모든 바이트가 0 인 픽셀 묶음.Pixel data with every byte 0.

필드fieldpub width: u32#0.4.0 부터since 0.4.0소스source

폭. (픽셀)

Width. (pixels)

반환Returnsu32

필드fieldpub height: u32#0.4.0 부터since 0.4.0소스source

높이. (픽셀)

Height. (pixels)

반환Returnsu32

필드fieldpub data: Vec<u8>#0.4.0 부터since 0.4.0소스source

픽셀. (줄마다 왼쪽에서 오른쪽으로, 픽셀마다 R, G, B, A 바이트, 폭 x 높이 x 4 개)

Pixels. (row by row from left to right, R, G, B, A bytes per pixel, width x height x 4 of them)

반환ReturnsVec<u8>

CanvasRadiusenum traits Clone, Copy, Debug, PartialEq, From<f64>, From<(f64, f64)>

소스source

둥근 사각형 모서리 반지름. (원본 roundRect 의 수 또는 DOMPointInit {x, y})

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

이름Name값Value설명Description
CircularCircular(f32)가로와 세로가 같은 반지름. (원본의 수)A radius equal horizontally and vertically. (a number in the original)
EllipticalElliptical{ x: f32, y: f32, }가로 x, 세로 y 반지름. (원본 DOMPointInit {x, y})Horizontal x and vertical y radii. (the original DOMPointInit {x, y})

CanvasGradientKindenum traits Clone, Copy, Debug, PartialEq

소스source

그라데이션 종류.

Gradient kind.

이름Name값Value설명Description
LinearLinear{ start_x: f32, start_y: f32, end_x: f32, end_y: f32, }원본 createLinearGradient(x0, y0, x1, y1)The original createLinearGradient(x0, y0, x1, y1)
RadialRadial{ start_x: f32, start_y: f32, start_radius: f32, end_x: f32, end_y: f32, end_radius: f32, }원본 createRadialGradient(x0, y0, r0, x1, y1, r1)The original createRadialGradient(x0, y0, r0, x1, y1, r1)
ConicConic{ start_angle: f32, center_x: f32, center_y: f32, }원본 createConicGradient(startAngle, x, y)The original createConicGradient(startAngle, x, y)

CanvasPatternRepetitionenum traits Clone, Copy, Debug, PartialEq, Eq

소스source

패턴 되풀이. (원본 "repeat", "repeat-x", "repeat-y", "no-repeat")

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

이름Name설명Description
Repeat가로세로로 되풀이. (원본 "repeat")Repeats horizontally and vertically. (the original "repeat")
RepeatX가로로만 되풀이. (원본 "repeat-x")Repeats only horizontally. (the original "repeat-x")
RepeatY세로로만 되풀이. (원본 "repeat-y")Repeats only vertically. (the original "repeat-y")
NoRepeat한 장만. (원본 "no-repeat")A single copy. (the original "no-repeat")
메서드methodpub fn get_name(&self) -> &'static str#0.4.0 부터since 0.4.0소스source

원본 글.

Original text.

반환Returns&'static str "repeat", "repeat-x", "repeat-y", "no-repeat" 가운데 하나.One of "repeat", "repeat-x", "repeat-y", "no-repeat".

CanvasStyleenum traits Clone, Debug, PartialEq, From<Color>, From<&str>, From<&String>, From<CanvasGradient>, From<&CanvasGradient>, From<CanvasPattern>, From<&CanvasPattern>

소스source

칠할 것. (원본 fillStyle, strokeStyle 의 색 글, CanvasGradient, CanvasPattern)

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

이름Name값Value설명Description
ColorColor(Color)단색.Solid color.
GradientGradient(CanvasGradient)그라데이션.Gradient.
PatternPattern(CanvasPattern)패턴.Pattern.

CanvasFillRuleenum traits Clone, Copy, Debug, Default, PartialEq, Eq

소스source

채우기 규칙. (원본 "nonzero", "evenodd")

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

이름Name설명Description
NonZero감긴 수가 0 이 아니면 안. (원본 "nonzero", 기본)Inside if the winding number is not 0. (the original "nonzero", default)
EvenOdd겹친 수가 홀수면 안. (원본 "evenodd")Inside if the crossing count is odd. (the original "evenodd")

CanvasLineCapenum traits Clone, Copy, Debug, Default, PartialEq, Eq

소스source

선 끝. (원본 lineCap)

Line cap. (the original lineCap)

이름Name설명Description
Butt끝에서 자른다. (원본 "butt", 기본)Cut off at the end. (the original "butt", default)
Round반원을 붙인다. (원본 "round")Adds a half circle. (the original "round")
Square굵기의 반만큼 네모를 붙인다. (원본 "square")Adds a square extending half the line width. (the original "square")

CanvasLineJoinenum traits Clone, Copy, Debug, Default, PartialEq, Eq

소스source

선 이음. (원본 lineJoin)

Line join. (the original lineJoin)

이름Name설명Description
Miter뾰족하게 늘인다. (원본 "miter", 기본, 뾰족 이음 한계를 넘으면 Bevel 처럼 깎는다)Extends to a sharp point. (the original "miter", default, beveled like Bevel when the miter limit is exceeded)
Round둥글게 잇는다. (원본 "round")Joins with a round. (the original "round")
Bevel모서리를 깎는다. (원본 "bevel")Cuts off the corner. (the original "bevel")

CanvasTextAlignenum traits Clone, Copy, Debug, Default, PartialEq, Eq

소스source

글 가로 정렬. (원본 textAlign, start 와 end 는 왼쪽에서 오른쪽 글로 본다)

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

이름Name설명Description
Startx 에서 글이 시작한다. (원본 "start", 기본)The text starts at x. (the original "start", default)
Endx 에서 글이 끝난다. (원본 "end")The text ends at x. (the original "end")
Leftx 가 글의 왼쪽 끝. (원본 "left")x is the left edge of the text. (the original "left")
Rightx 가 글의 오른쪽 끝. (원본 "right")x is the right edge of the text. (the original "right")
Centerx 가 글의 가운데. (원본 "center")x is the center of the text. (the original "center")

CanvasTextBaselineenum traits Clone, Copy, Debug, Default, PartialEq, Eq

소스source

글 기준선. (원본 textBaseline)

Text baseline. (the original textBaseline)

이름Name설명Description
Topy 가 em 상자의 위. (원본 "top")y is the top of the em box. (the original "top")
Hangingy 가 매다는 기준선. (원본 "hanging", 데바나가리 같은 글의 위쪽 기준선)y is the hanging baseline. (the original "hanging", the top baseline of scripts like Devanagari)
Middley 가 em 상자의 가운데. (원본 "middle")y is the middle of the em box. (the original "middle")
Alphabeticy 가 알파벳 기준선. (원본 "alphabetic", 기본)y is the alphabetic baseline. (the original "alphabetic", default)
Ideographicy 가 표의 문자 기준선. (원본 "ideographic")y is the ideographic baseline. (the original "ideographic")
Bottomy 가 em 상자의 아래. (원본 "bottom")y is the bottom of the em box. (the original "bottom")

CanvasImageSourceenum traits Clone, Copy, From<&'a crate::core::image::Image>, From<&'a std::rc::Rc<crate::core::image::Image>>, From<&'a Canvas2D>

소스source

그릴 그림. (원본 drawImage 와 createPattern 이 받는 그림: 엔진 Image, 다른 캔버스)

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

이름Name값Value설명Description
ImageImage(&'a crate::core::image::Image)엔진 그림. (GPU 에 올리며 CPU 픽셀을 놓았으면 텍스처에서 되읽는다)Engine image. (if its CPU pixels were released when uploaded to the GPU, they are read back from the texture)
CanvasCanvas(&'a Canvas2D)다른 캔버스.Another canvas.
메서드methodpub fn get_size(&self) -> (u32, u32)#0.4.0 부터since 0.4.0소스source

크기.

Size.

반환Returns(u32, u32) (폭, 높이). (픽셀)(width, height). (pixels)