Skip to main content

script/dom/canvas/2d/
canvasrenderingcontext2d.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use euclid::default::Size2D;
7use js::context::{JSContext, NoGC};
8use pixels::Snapshot;
9use script_bindings::reflector::{AssociatedMemory, Reflector, reflect_dom_object_with_cx};
10use servo_base::{Epoch, generic_channel};
11use servo_canvas_traits::canvas::{CanvasCommand, CanvasId};
12use webrender_api::ImageKey;
13
14use super::canvas_state::CanvasState;
15use crate::canvas_context::{CanvasContext, CanvasHelpers, HTMLCanvasElementOrOffscreenCanvas};
16use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::{
17    CanvasColorType, CanvasDirection, CanvasFillRule, CanvasImageSource, CanvasLineCap,
18    CanvasLineJoin, CanvasRenderingContext2DMethods, CanvasRenderingContext2DSettings,
19    CanvasTextAlign, CanvasTextBaseline, PredefinedColorSpace,
20};
21use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::DOMMatrix2DInit;
22use crate::dom::bindings::codegen::UnionTypes::{
23    HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas,
24    StringOrCanvasGradientOrCanvasPattern,
25};
26use crate::dom::bindings::error::{ErrorResult, Fallible};
27use crate::dom::bindings::num::Finite;
28use crate::dom::bindings::reflector::DomGlobal;
29use crate::dom::bindings::root::{Dom, DomRoot};
30use crate::dom::bindings::str::DOMString;
31use crate::dom::canvasgradient::CanvasGradient;
32use crate::dom::canvaspattern::CanvasPattern;
33use crate::dom::dommatrix::DOMMatrix;
34use crate::dom::globalscope::GlobalScope;
35use crate::dom::html::htmlcanvaselement::HTMLCanvasElement;
36use crate::dom::imagedata::ImageData;
37use crate::dom::path2d::Path2D;
38use crate::dom::textmetrics::TextMetrics;
39
40// https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d
41#[dom_struct]
42pub(crate) struct CanvasRenderingContext2D {
43    reflector_: Reflector<AssociatedMemory>,
44    canvas: HTMLCanvasElementOrOffscreenCanvas,
45    canvas_state: CanvasState,
46    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-alpha>
47    alpha: bool,
48    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-desynchronized>
49    desynchronized: bool,
50    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-color-space>
51    color_space: PredefinedColorSpace,
52    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-color-type>
53    color_type: CanvasColorType,
54    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-will-read-frequently>
55    will_read_frequently: bool,
56}
57
58impl CanvasRenderingContext2D {
59    const RGBA8_BYTES_PER_PIXEL: usize = 4;
60    /// Ideally this would be two bitmap buffers, unfortunately we currently have ~4 copies
61    /// which are all retained until GC:
62    ///
63    /// 1. The draw target's backing bitmap in the canvas paint thread
64    ///    (`CanvasData::draw_target`, e.g. `pixmap` in `VelloCPUDrawTarget`).
65    /// 2. Additional backend resources (approximated with 1 bitmap buffer, actually depends on backend):
66    ///    e.g. `ctx` and `resources` in `VelloCPUDrawTarget` for vello_cpu.
67    ///    TODO: #46785 tracks getting accurate statistics from the backend.
68    /// 3. `CachedImageData::Raw` in WebRender (cpu memory copy).
69    /// 4. GPU memory in webrender / driver (also lives in RAM on unified memory systems).
70    ///
71    /// This metric is only used to inform the GC about memory pressure, so it doesn't need to
72    /// be completely accurate, but undercounting may delay GCs and hence increase memory usage.
73    /// On mobile devices this slightly undercounts (usually unified memory), on desktop this
74    /// slightly overcounts, since GPU memory is separate.
75    const ASSOCIATED_MEMORY_BUFFER_COUNT: usize = 4;
76
77    fn associated_memory_size(size: Size2D<u64>) -> usize {
78        (size.width as usize)
79            .saturating_mul(size.height as usize)
80            .saturating_mul(Self::RGBA8_BYTES_PER_PIXEL)
81            .saturating_mul(Self::ASSOCIATED_MEMORY_BUFFER_COUNT)
82    }
83
84    pub(crate) fn update_associated_memory_size(&self) {
85        self.reflector_.update_memory_size(
86            self,
87            Self::associated_memory_size(self.canvas_state.bitmap_dimensions()),
88        );
89    }
90
91    /// <https://html.spec.whatwg.org/multipage/#canvas-setting-init-bitmap>
92    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
93    pub(crate) fn new_inherited(
94        global: &GlobalScope,
95        canvas: HTMLCanvasElementOrOffscreenCanvas,
96        size: Size2D<u32>,
97        settings: &CanvasRenderingContext2DSettings,
98    ) -> Option<CanvasRenderingContext2D> {
99        let canvas_state =
100            CanvasState::new(global, Size2D::new(size.width as u64, size.height as u64))?;
101        Some(CanvasRenderingContext2D {
102            reflector_: Reflector::new(),
103            canvas,
104            canvas_state,
105            // Step 1. Set context's alpha to settings["alpha"].
106            alpha: settings.alpha,
107            // Step 2. Set context's desynchronized to settings["desynchronized"].
108            desynchronized: settings.desynchronized,
109            // Step 3. Set context's color space to settings["colorSpace"].
110            color_space: settings.colorSpace,
111            // Step 4. Set context's color type to settings["colorType"].
112            color_type: settings.colorType,
113            // Step 5. Set context's will read frequently to settings["willReadFrequently"].
114            will_read_frequently: settings.willReadFrequently,
115        })
116    }
117
118    pub(crate) fn new(
119        cx: &mut JSContext,
120        global: &GlobalScope,
121        canvas: &HTMLCanvasElement,
122        size: Size2D<u32>,
123        settings: &CanvasRenderingContext2DSettings,
124    ) -> Option<DomRoot<CanvasRenderingContext2D>> {
125        CanvasRenderingContext2D::new_inherited(
126            global,
127            HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(Dom::from_ref(canvas)),
128            size,
129            settings,
130        )
131        .map(|context| {
132            let context = reflect_dom_object_with_cx(Box::new(context), global, cx);
133            context.update_associated_memory_size();
134            context
135        })
136    }
137
138    pub(crate) fn send_canvas_command_immediate(&self, msg: CanvasCommand) {
139        self.canvas_state.send_canvas_command_immediate(msg)
140    }
141
142    pub(crate) fn set_image_key(&self, image_key: ImageKey) {
143        self.canvas_state.set_image_key(image_key);
144    }
145
146    pub(crate) fn update_rendering(&self, canvas_epoch: Epoch) -> bool {
147        if !self.onscreen() {
148            return false;
149        }
150        self.canvas_state.update_rendering(Some(canvas_epoch))
151    }
152}
153
154impl CanvasContext for CanvasRenderingContext2D {
155    type ID = CanvasId;
156
157    fn context_id(&self) -> Self::ID {
158        self.canvas_state.get_canvas_id()
159    }
160
161    fn canvas(&self) -> Option<RootedHTMLCanvasElementOrOffscreenCanvas> {
162        Some(RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas))
163    }
164
165    fn resize(&self) {
166        self.canvas_state.set_bitmap_dimensions(self.size().cast());
167        self.update_associated_memory_size();
168    }
169
170    fn reset_bitmap(&self) {
171        self.canvas_state.reset_bitmap()
172    }
173
174    fn get_image_data(&self) -> Option<Snapshot> {
175        if !self.canvas_state.is_paintable() {
176            return None;
177        }
178
179        let (sender, receiver) = generic_channel::channel().unwrap();
180        self.canvas_state
181            .send_canvas_command_immediate(CanvasCommand::GetImageData(None, sender));
182        Some(receiver.recv().unwrap().to_owned())
183    }
184
185    fn origin_is_clean(&self) -> bool {
186        self.canvas_state.origin_is_clean()
187    }
188
189    fn mark_as_dirty(&self) {
190        self.canvas.mark_as_dirty();
191    }
192}
193
194// We add a guard to each of methods by the spec:
195// http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas_CR/
196//
197// > Except where otherwise specified, for the 2D context interface,
198// > any method call with a numeric argument whose value is infinite or a NaN value must be ignored.
199//
200//  Restricted values are guarded in glue code. Therefore we need not add a guard.
201//
202// FIXME: this behavior should might be generated by some annotations to idl.
203impl CanvasRenderingContext2DMethods<crate::DomTypeHolder> for CanvasRenderingContext2D {
204    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-canvas-getcontextattributes>
205    fn GetContextAttributes(&self) -> CanvasRenderingContext2DSettings {
206        // The getContextAttributes() method steps are to return «[ "alpha" → this's alpha,
207        // "desynchronized" → this's desynchronized, "colorSpace" → this's color space,
208        // "colorType" → this's color type, "willReadFrequently" → this's will read frequently ]».
209        CanvasRenderingContext2DSettings {
210            alpha: self.alpha,
211            desynchronized: self.desynchronized,
212            colorSpace: self.color_space,
213            colorType: self.color_type,
214            willReadFrequently: self.will_read_frequently,
215        }
216    }
217
218    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-canvas>
219    fn Canvas(&self) -> DomRoot<HTMLCanvasElement> {
220        match &self.canvas {
221            HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(canvas) => canvas.as_rooted(),
222            _ => panic!("Should not be called from offscreen canvas"),
223        }
224    }
225
226    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-save>
227    fn Save(&self) {
228        self.canvas_state.save()
229    }
230
231    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-restore>
232    fn Restore(&self) {
233        self.canvas_state.restore()
234    }
235
236    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-reset>
237    fn Reset(&self) {
238        self.canvas_state.reset()
239    }
240
241    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-scale>
242    fn Scale(&self, x: f64, y: f64) {
243        self.canvas_state.scale(x, y)
244    }
245
246    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate>
247    fn Rotate(&self, angle: f64) {
248        self.canvas_state.rotate(angle)
249    }
250
251    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-translate>
252    fn Translate(&self, x: f64, y: f64) {
253        self.canvas_state.translate(x, y)
254    }
255
256    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-transform>
257    fn Transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
258        self.canvas_state.transform(a, b, c, d, e, f)
259    }
260
261    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-gettransform>
262    fn GetTransform(&self, cx: &mut JSContext) -> DomRoot<DOMMatrix> {
263        self.canvas_state.get_transform(&self.global(), cx)
264    }
265
266    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform>
267    fn SetTransform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> ErrorResult {
268        self.canvas_state.set_transform(a, b, c, d, e, f);
269        Ok(())
270    }
271
272    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform-matrix>
273    fn SetTransform_(&self, transform: &DOMMatrix2DInit) -> ErrorResult {
274        self.canvas_state.set_transform_(transform)
275    }
276
277    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform>
278    fn ResetTransform(&self) {
279        self.canvas_state.reset_transform()
280    }
281
282    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha>
283    fn GlobalAlpha(&self) -> f64 {
284        self.canvas_state.global_alpha()
285    }
286
287    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha>
288    fn SetGlobalAlpha(&self, alpha: f64) {
289        self.canvas_state.set_global_alpha(alpha)
290    }
291
292    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation>
293    fn GlobalCompositeOperation(&self) -> DOMString {
294        self.canvas_state.global_composite_operation()
295    }
296
297    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation>
298    fn SetGlobalCompositeOperation(&self, op_str: DOMString) {
299        self.canvas_state.set_global_composite_operation(op_str)
300    }
301
302    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect>
303    fn FillRect(&self, x: f64, y: f64, width: f64, height: f64) {
304        self.canvas_state.fill_rect(x, y, width, height);
305        self.mark_as_dirty();
306    }
307
308    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect>
309    fn ClearRect(&self, x: f64, y: f64, width: f64, height: f64) {
310        self.canvas_state.clear_rect(x, y, width, height);
311        self.mark_as_dirty();
312    }
313
314    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect>
315    fn StrokeRect(&self, x: f64, y: f64, width: f64, height: f64) {
316        self.canvas_state.stroke_rect(x, y, width, height);
317        self.mark_as_dirty();
318    }
319
320    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath>
321    fn BeginPath(&self) {
322        self.canvas_state.begin_path()
323    }
324
325    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath>
326    fn ClosePath(&self) {
327        self.canvas_state.close_path()
328    }
329
330    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-fill>
331    fn Fill(&self, fill_rule: CanvasFillRule) {
332        self.canvas_state.fill(fill_rule);
333        self.mark_as_dirty();
334    }
335
336    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-fill>
337    fn Fill_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
338        self.canvas_state.fill_(path.segments(), fill_rule);
339        self.mark_as_dirty();
340    }
341
342    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke>
343    fn Stroke(&self) {
344        self.canvas_state.stroke();
345        self.mark_as_dirty();
346    }
347
348    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke>
349    fn Stroke_(&self, path: &Path2D) {
350        self.canvas_state.stroke_(path.segments());
351        self.mark_as_dirty();
352    }
353
354    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-clip>
355    fn Clip(&self, fill_rule: CanvasFillRule) {
356        self.canvas_state.clip(fill_rule)
357    }
358
359    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-clip>
360    fn Clip_(&self, path: &Path2D, fill_rule: CanvasFillRule) {
361        self.canvas_state.clip_(path.segments(), fill_rule)
362    }
363
364    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath>
365    fn IsPointInPath(&self, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
366        self.canvas_state
367            .is_point_in_path(&self.global(), x, y, fill_rule)
368    }
369
370    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath>
371    fn IsPointInPath_(&self, path: &Path2D, x: f64, y: f64, fill_rule: CanvasFillRule) -> bool {
372        self.canvas_state
373            .is_point_in_path_(&self.global(), path.segments(), x, y, fill_rule)
374    }
375
376    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-filltext>
377    fn FillText(&self, text: DOMString, x: f64, y: f64, max_width: Option<f64>) {
378        self.canvas_state.fill_text(
379            &self.global(),
380            self.canvas.canvas().as_deref(),
381            text,
382            x,
383            y,
384            max_width,
385        );
386        self.mark_as_dirty();
387    }
388
389    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-stroketext>
390    fn StrokeText(&self, text: DOMString, x: f64, y: f64, max_width: Option<f64>) {
391        self.canvas_state.stroke_text(
392            &self.global(),
393            self.canvas.canvas().as_deref(),
394            text,
395            x,
396            y,
397            max_width,
398        );
399        self.mark_as_dirty();
400    }
401
402    /// <https://html.spec.whatwg.org/multipage/#textmetrics>
403    fn MeasureText(&self, cx: &mut JSContext, text: DOMString) -> DomRoot<TextMetrics> {
404        self.canvas_state
405            .measure_text(&self.global(), self.canvas.canvas().as_deref(), text, cx)
406    }
407
408    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-font>
409    fn Font(&self) -> DOMString {
410        self.canvas_state.font()
411    }
412
413    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-font>
414    fn SetFont(&self, value: DOMString) {
415        self.canvas_state
416            .set_font(self.canvas.canvas().as_deref(), value)
417    }
418
419    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign>
420    fn TextAlign(&self) -> CanvasTextAlign {
421        self.canvas_state.text_align()
422    }
423
424    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign>
425    fn SetTextAlign(&self, value: CanvasTextAlign) {
426        self.canvas_state.set_text_align(value)
427    }
428
429    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-textbaseline>
430    fn TextBaseline(&self) -> CanvasTextBaseline {
431        self.canvas_state.text_baseline()
432    }
433
434    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-textbaseline>
435    fn SetTextBaseline(&self, value: CanvasTextBaseline) {
436        self.canvas_state.set_text_baseline(value)
437    }
438
439    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-direction>
440    fn Direction(&self) -> CanvasDirection {
441        self.canvas_state.direction()
442    }
443
444    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-direction>
445    fn SetDirection(&self, value: CanvasDirection) {
446        self.canvas_state.set_direction(value)
447    }
448
449    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
450    fn DrawImage(&self, image: CanvasImageSource, dx: f64, dy: f64) -> ErrorResult {
451        self.canvas_state
452            .draw_image(self.canvas.canvas().as_deref(), image, dx, dy)
453    }
454
455    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
456    fn DrawImage_(
457        &self,
458        image: CanvasImageSource,
459        dx: f64,
460        dy: f64,
461        dw: f64,
462        dh: f64,
463    ) -> ErrorResult {
464        self.canvas_state
465            .draw_image_(self.canvas.canvas().as_deref(), image, dx, dy, dw, dh)
466    }
467
468    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
469    fn DrawImage__(
470        &self,
471        image: CanvasImageSource,
472        sx: f64,
473        sy: f64,
474        sw: f64,
475        sh: f64,
476        dx: f64,
477        dy: f64,
478        dw: f64,
479        dh: f64,
480    ) -> ErrorResult {
481        self.canvas_state.draw_image__(
482            self.canvas.canvas().as_deref(),
483            image,
484            sx,
485            sy,
486            sw,
487            sh,
488            dx,
489            dy,
490            dw,
491            dh,
492        )
493    }
494
495    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto>
496    fn MoveTo(&self, x: f64, y: f64) {
497        self.canvas_state.move_to(x, y)
498    }
499
500    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto>
501    fn LineTo(&self, x: f64, y: f64) {
502        self.canvas_state.line_to(x, y)
503    }
504
505    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-rect>
506    fn Rect(&self, x: f64, y: f64, width: f64, height: f64) {
507        self.canvas_state.rect(x, y, width, height)
508    }
509
510    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto>
511    fn QuadraticCurveTo(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
512        self.canvas_state.quadratic_curve_to(cpx, cpy, x, y)
513    }
514
515    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto>
516    fn BezierCurveTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
517        self.canvas_state
518            .bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y)
519    }
520
521    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-arc>
522    fn Arc(&self, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) -> ErrorResult {
523        self.canvas_state.arc(x, y, r, start, end, ccw)
524    }
525
526    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto>
527    fn ArcTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
528        self.canvas_state.arc_to(cp1x, cp1y, cp2x, cp2y, r)
529    }
530
531    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse>
532    fn Ellipse(
533        &self,
534        x: f64,
535        y: f64,
536        rx: f64,
537        ry: f64,
538        rotation: f64,
539        start: f64,
540        end: f64,
541        ccw: bool,
542    ) -> ErrorResult {
543        self.canvas_state
544            .ellipse(x, y, rx, ry, rotation, start, end, ccw)
545    }
546
547    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled>
548    fn ImageSmoothingEnabled(&self) -> bool {
549        self.canvas_state.image_smoothing_enabled()
550    }
551
552    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled>
553    fn SetImageSmoothingEnabled(&self, value: bool) {
554        self.canvas_state.set_image_smoothing_enabled(value)
555    }
556
557    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle>
558    fn StrokeStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
559        self.canvas_state.stroke_style()
560    }
561
562    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle>
563    fn SetStrokeStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
564        self.canvas_state
565            .set_stroke_style(self.canvas.canvas().as_deref(), value)
566    }
567
568    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle>
569    fn FillStyle(&self) -> StringOrCanvasGradientOrCanvasPattern {
570        self.canvas_state.fill_style()
571    }
572
573    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle>
574    fn SetFillStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) {
575        self.canvas_state
576            .set_fill_style(self.canvas.canvas().as_deref(), value)
577    }
578
579    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata>
580    fn CreateImageData(
581        &self,
582        cx: &mut JSContext,
583        sw: i32,
584        sh: i32,
585    ) -> Fallible<DomRoot<ImageData>> {
586        self.canvas_state
587            .create_image_data(cx, &self.global(), sw, sh)
588    }
589
590    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata>
591    fn CreateImageData_(
592        &self,
593        cx: &mut JSContext,
594        imagedata: &ImageData,
595    ) -> Fallible<DomRoot<ImageData>> {
596        self.canvas_state
597            .create_image_data_(cx, &self.global(), imagedata)
598    }
599
600    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata>
601    fn GetImageData(
602        &self,
603        cx: &mut JSContext,
604        sx: i32,
605        sy: i32,
606        sw: i32,
607        sh: i32,
608    ) -> Fallible<DomRoot<ImageData>> {
609        self.canvas_state
610            .get_image_data(cx, self.canvas.size(), &self.global(), sx, sy, sw, sh)
611    }
612
613    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata>
614    fn PutImageData(&self, no_gc: &NoGC, imagedata: &ImageData, dx: i32, dy: i32) {
615        self.canvas_state
616            .put_image_data(no_gc, self.canvas.size(), imagedata, dx, dy);
617        self.mark_as_dirty();
618    }
619
620    // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
621    fn PutImageData_(
622        &self,
623        no_gc: &NoGC,
624        imagedata: &ImageData,
625        dx: i32,
626        dy: i32,
627        dirty_x: i32,
628        dirty_y: i32,
629        dirty_width: i32,
630        dirty_height: i32,
631    ) {
632        self.canvas_state.put_image_data_(
633            no_gc,
634            self.canvas.size(),
635            imagedata,
636            dx,
637            dy,
638            dirty_x,
639            dirty_y,
640            dirty_width,
641            dirty_height,
642        );
643        self.mark_as_dirty();
644    }
645
646    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient>
647    fn CreateLinearGradient(
648        &self,
649        cx: &mut JSContext,
650        x0: Finite<f64>,
651        y0: Finite<f64>,
652        x1: Finite<f64>,
653        y1: Finite<f64>,
654    ) -> DomRoot<CanvasGradient> {
655        self.canvas_state
656            .create_linear_gradient(&self.global(), cx, x0, y0, x1, y1)
657    }
658
659    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient>
660    fn CreateRadialGradient(
661        &self,
662        cx: &mut JSContext,
663        x0: Finite<f64>,
664        y0: Finite<f64>,
665        r0: Finite<f64>,
666        x1: Finite<f64>,
667        y1: Finite<f64>,
668        r1: Finite<f64>,
669    ) -> Fallible<DomRoot<CanvasGradient>> {
670        self.canvas_state
671            .create_radial_gradient(&self.global(), cx, x0, y0, r0, x1, y1, r1)
672    }
673
674    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern>
675    fn CreatePattern(
676        &self,
677        cx: &mut JSContext,
678        image: CanvasImageSource,
679        repetition: DOMString,
680    ) -> Fallible<Option<DomRoot<CanvasPattern>>> {
681        self.canvas_state
682            .create_pattern(&self.global(), cx, image, repetition)
683    }
684
685    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth>
686    fn LineWidth(&self) -> f64 {
687        self.canvas_state.line_width()
688    }
689
690    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth>
691    fn SetLineWidth(&self, width: f64) {
692        self.canvas_state.set_line_width(width)
693    }
694
695    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap>
696    fn LineCap(&self) -> CanvasLineCap {
697        self.canvas_state.line_cap()
698    }
699
700    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap>
701    fn SetLineCap(&self, cap: CanvasLineCap) {
702        self.canvas_state.set_line_cap(cap)
703    }
704
705    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin>
706    fn LineJoin(&self) -> CanvasLineJoin {
707        self.canvas_state.line_join()
708    }
709
710    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin>
711    fn SetLineJoin(&self, join: CanvasLineJoin) {
712        self.canvas_state.set_line_join(join)
713    }
714
715    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit>
716    fn MiterLimit(&self) -> f64 {
717        self.canvas_state.miter_limit()
718    }
719
720    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit>
721    fn SetMiterLimit(&self, limit: f64) {
722        self.canvas_state.set_miter_limit(limit)
723    }
724
725    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-setlinedash>
726    fn SetLineDash(&self, segments: Vec<f64>) {
727        self.canvas_state.set_line_dash(segments);
728    }
729
730    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-getlinedash>
731    fn GetLineDash(&self) -> Vec<f64> {
732        self.canvas_state.line_dash()
733    }
734
735    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
736    fn LineDashOffset(&self) -> f64 {
737        self.canvas_state.line_dash_offset()
738    }
739
740    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
741    fn SetLineDashOffset(&self, offset: f64) {
742        self.canvas_state.set_line_dash_offset(offset);
743    }
744
745    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx>
746    fn ShadowOffsetX(&self) -> f64 {
747        self.canvas_state.shadow_offset_x()
748    }
749
750    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx>
751    fn SetShadowOffsetX(&self, value: f64) {
752        self.canvas_state.set_shadow_offset_x(value)
753    }
754
755    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety>
756    fn ShadowOffsetY(&self) -> f64 {
757        self.canvas_state.shadow_offset_y()
758    }
759
760    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety>
761    fn SetShadowOffsetY(&self, value: f64) {
762        self.canvas_state.set_shadow_offset_y(value)
763    }
764
765    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur>
766    fn ShadowBlur(&self) -> f64 {
767        self.canvas_state.shadow_blur()
768    }
769
770    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur>
771    fn SetShadowBlur(&self, value: f64) {
772        self.canvas_state.set_shadow_blur(value)
773    }
774
775    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor>
776    fn ShadowColor(&self) -> DOMString {
777        self.canvas_state.shadow_color()
778    }
779
780    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor>
781    fn SetShadowColor(&self, value: DOMString) {
782        self.canvas_state
783            .set_shadow_color(self.canvas.canvas().as_deref(), value)
784    }
785}