script/dom/canvas/2d/
canvasgradient.rs1#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use script_bindings::cell::DomRefCell;
10use script_bindings::reflector::{Reflector, reflect_dom_object};
11use servo_canvas_traits::canvas::{
12 CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle,
13};
14
15use super::canvas_state::parse_color;
16use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasGradientMethods;
17use crate::dom::bindings::error::{Error, ErrorResult};
18use crate::dom::bindings::num::Finite;
19use crate::dom::bindings::root::DomRoot;
20use crate::dom::bindings::str::DOMString;
21use crate::dom::globalscope::GlobalScope;
22
23#[dom_struct]
25pub(crate) struct CanvasGradient {
26 reflector_: Reflector,
27 style: CanvasGradientStyle,
28 #[no_trace]
29 stops: DomRefCell<Vec<CanvasGradientStop>>,
30}
31
32#[derive(Clone, JSTraceable, MallocSizeOf)]
33pub(crate) enum CanvasGradientStyle {
34 Linear(#[no_trace] LinearGradientStyle),
35 Radial(#[no_trace] RadialGradientStyle),
36}
37
38impl CanvasGradient {
39 fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient {
40 CanvasGradient {
41 reflector_: Reflector::new(),
42 style,
43 stops: DomRefCell::new(Vec::new()),
44 }
45 }
46
47 pub(crate) fn new(
48 global: &GlobalScope,
49 cx: &mut JSContext,
50 style: CanvasGradientStyle,
51 ) -> DomRoot<CanvasGradient> {
52 reflect_dom_object(cx, Box::new(CanvasGradient::new_inherited(style)), global)
53 }
54}
55
56impl CanvasGradientMethods<crate::DomTypeHolder> for CanvasGradient {
57 fn AddColorStop(
59 &self,
60 cx: &mut JSContext,
61 offset: Finite<f64>,
62 color: DOMString,
63 ) -> ErrorResult {
64 if *offset < 0f64 || *offset > 1f64 {
65 return Err(Error::IndexSize(None));
66 }
67
68 let color = match parse_color(cx, None, &color) {
69 Ok(color) => color,
70 Err(_) => return Err(Error::Syntax(None)),
71 };
72
73 self.stops.borrow_mut().push(CanvasGradientStop {
74 offset: (*offset),
75 color,
76 });
77 Ok(())
78 }
79}
80
81pub(crate) trait ToFillOrStrokeStyle {
82 fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle;
83}
84
85impl ToFillOrStrokeStyle for &CanvasGradient {
86 fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle {
87 let gradient_stops = self.stops.borrow().clone();
88 match self.style {
89 CanvasGradientStyle::Linear(ref gradient) => {
90 FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(
91 gradient.x0,
92 gradient.y0,
93 gradient.x1,
94 gradient.y1,
95 gradient_stops,
96 ))
97 },
98 CanvasGradientStyle::Radial(ref gradient) => {
99 FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(
100 gradient.x0,
101 gradient.y0,
102 gradient.r0,
103 gradient.x1,
104 gradient.y1,
105 gradient.r1,
106 gradient_stops,
107 ))
108 },
109 }
110 }
111}