Skip to main content

script/dom/html/embedded_content/
htmlcanvaselement.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 std::cell::Cell;
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use euclid::default::Size2D;
10use html5ever::{LocalName, Prefix, local_name, ns};
11use js::context::NoGC;
12use js::error::throw_type_error;
13use js::rust::{HandleObject, HandleValue};
14use layout_api::HTMLCanvasData;
15use pixels::{EncodedImageType, Snapshot};
16use rustc_hash::FxHashMap;
17use script_bindings::cell::{DomRefCell, Ref};
18#[cfg(feature = "webgl")]
19use script_bindings::reflector::DomObject;
20use script_bindings::weakref::WeakRef;
21use servo_base::Epoch;
22#[cfg(feature = "webgl")]
23use servo_canvas_traits::webgl::{GLContextAttributes, WebGLVersion};
24use servo_constellation_traits::BlobImpl;
25#[cfg(feature = "webgpu")]
26use servo_constellation_traits::ScriptToConstellationMessage;
27use servo_media::streams::MediaStreamType;
28use servo_media::streams::registry::MediaStreamId;
29use style::attr::AttrValue;
30use webrender_api::ImageKey;
31
32use crate::canvas_context::{CanvasContext, RenderingContext};
33#[cfg(feature = "webgl")]
34use crate::conversions::Convert;
35use crate::dom::bindings::callback::{ExceptionHandling, RootedCallback, TracedCallback};
36use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DSettings;
37use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::{
38    BlobCallback, HTMLCanvasElementMethods, RenderingContext as RootedRenderingContext,
39};
40use crate::dom::bindings::codegen::Bindings::MediaStreamBinding::MediaStreamMethods;
41#[cfg(feature = "webgl")]
42use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes;
43use crate::dom::bindings::codegen::UnionTypes::HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas;
44use crate::dom::bindings::conversions::ConversionResult;
45use crate::dom::bindings::error::{Error, Fallible};
46use crate::dom::bindings::inheritance::Castable;
47use crate::dom::bindings::num::Finite;
48use crate::dom::bindings::refcounted::Trusted;
49use crate::dom::bindings::reflector::DomGlobal;
50use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom};
51use crate::dom::bindings::str::{DOMString, USVString};
52use crate::dom::blob::Blob;
53use crate::dom::canvasrenderingcontext2d::CanvasRenderingContext2D;
54use crate::dom::document::Document;
55use crate::dom::element::attributes::storage::AttrRef;
56use crate::dom::element::{AttributeMutation, Element};
57use crate::dom::html::htmlelement::HTMLElement;
58use crate::dom::imagebitmaprenderingcontext::ImageBitmapRenderingContext;
59use crate::dom::mediastream::MediaStream;
60use crate::dom::mediastreamtrack::MediaStreamTrack;
61use crate::dom::node::virtualmethods::VirtualMethods;
62use crate::dom::node::{Node, NodeDamage, NodeTraits};
63use crate::dom::offscreencanvas::OffscreenCanvas;
64use crate::dom::values::UNSIGNED_LONG_MAX;
65#[cfg(feature = "webgl")]
66use crate::dom::webgl::webgl2renderingcontext::WebGL2RenderingContext;
67#[cfg(feature = "webgl")]
68use crate::dom::webgl::webglrenderingcontext::WebGLRenderingContext;
69#[cfg(feature = "webgpu")]
70use crate::dom::webgpu::gpucanvascontext::GPUCanvasContext;
71
72const DEFAULT_WIDTH: u32 = 300;
73const DEFAULT_HEIGHT: u32 = 150;
74
75/// <https://html.spec.whatwg.org/multipage/#htmlcanvaselement>
76#[dom_struct]
77pub(crate) struct HTMLCanvasElement {
78    htmlelement: HTMLElement,
79
80    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-context-mode>
81    context_mode: DomRefCell<Option<RenderingContext>>,
82
83    /// This id along with [`Self::blob_callbacks`] are used to keep track of ongoing toBlob() calls.
84    callback_id: Cell<u32>,
85
86    /// This hashmap along with [`Self::callback_id`] are used to keep track of ongoing toBlob() calls.
87    blob_callbacks: DomRefCell<FxHashMap<u32, TracedCallback<BlobCallback>>>,
88
89    /// The [`ImageKey`] used to render this [`HTMLCanvasElement`] to the WebRender scene, if it
90    /// has a `RenderingContext`, otherwise `None`. Note that this key is owned by the `RenderingContext`
91    /// itself which will take care of cleaning it up.
92    #[no_trace]
93    image_key: Cell<Option<ImageKey>>,
94}
95
96impl HTMLCanvasElement {
97    fn new_inherited(
98        local_name: LocalName,
99        prefix: Option<Prefix>,
100        document: &Document,
101    ) -> HTMLCanvasElement {
102        HTMLCanvasElement {
103            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
104            context_mode: DomRefCell::new(None),
105            callback_id: Cell::new(0),
106            blob_callbacks: DomRefCell::new(FxHashMap::default()),
107            image_key: Default::default(),
108        }
109    }
110
111    pub(crate) fn new(
112        cx: &mut js::context::JSContext,
113        local_name: LocalName,
114        prefix: Option<Prefix>,
115        document: &Document,
116        proto: Option<HandleObject>,
117    ) -> DomRoot<HTMLCanvasElement> {
118        Node::reflect_weak_referenceable_node_with_proto(
119            cx,
120            Rc::new(HTMLCanvasElement::new_inherited(
121                local_name, prefix, document,
122            )),
123            document,
124            proto,
125        )
126    }
127
128    fn recreate_contexts_after_resize(&self) {
129        if let Some(ref context) = *self.context_mode.borrow() {
130            context.resize()
131        }
132    }
133
134    pub(crate) fn get_size(&self) -> Size2D<u32> {
135        Size2D::new(self.Width(), self.Height())
136    }
137
138    pub(crate) fn origin_is_clean(&self) -> bool {
139        match *self.context_mode.borrow() {
140            Some(ref context) => context.origin_is_clean(),
141            _ => true,
142        }
143    }
144
145    pub(crate) fn mark_as_dirty(&self) {
146        if let Some(ref context) = *self.context_mode.borrow() {
147            context.mark_as_dirty()
148        }
149    }
150
151    pub(crate) fn set_natural_width(&self, cx: &mut js::context::JSContext, value: u32) {
152        let value = if value > UNSIGNED_LONG_MAX {
153            DEFAULT_WIDTH
154        } else {
155            value
156        };
157        self.upcast::<Element>()
158            .set_attribute(cx, &html5ever::local_name!("width"), value.into());
159    }
160
161    pub(crate) fn set_natural_height(&self, cx: &mut js::context::JSContext, value: u32) {
162        let value = if value > UNSIGNED_LONG_MAX {
163            DEFAULT_HEIGHT
164        } else {
165            value
166        };
167        self.upcast::<Element>()
168            .set_attribute(cx, &html5ever::local_name!("height"), value.into());
169    }
170}
171
172impl LayoutDom<'_, HTMLCanvasElement> {
173    pub(crate) fn data(self) -> HTMLCanvasData {
174        let width_attr = self
175            .upcast::<Element>()
176            .get_attr_for_layout(&ns!(), &local_name!("width"));
177        let height_attr = self
178            .upcast::<Element>()
179            .get_attr_for_layout(&ns!(), &local_name!("height"));
180        HTMLCanvasData {
181            image_key: self.unsafe_get().image_key.get(),
182            width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
183            height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
184        }
185    }
186}
187
188impl HTMLCanvasElement {
189    pub(crate) fn context(&self) -> Option<Ref<'_, RenderingContext>> {
190        Ref::filter_map(self.context_mode.borrow(), |ctx| ctx.as_ref()).ok()
191    }
192
193    fn set_rendering_context(
194        &self,
195        no_gc: &NoGC,
196        make_rendering_context: impl FnOnce() -> RenderingContext,
197    ) {
198        self.upcast::<Node>()
199            .dirty(no_gc, NodeDamage::ContentOrHeritage);
200        self.context_mode
201            .safe_borrow_mut(no_gc)
202            .replace(make_rendering_context());
203
204        let Some(rendering_context) = &*self.context_mode.borrow() else {
205            return;
206        };
207
208        let get_image_key = || self.owner_window().image_cache().get_image_key();
209        let image_key = match rendering_context {
210            RenderingContext::Placeholder(..) => None,
211            RenderingContext::Context2d(..) => get_image_key(),
212            RenderingContext::BitmapRenderer(..) => get_image_key(),
213            #[cfg(feature = "webgl")]
214            RenderingContext::WebGL(..) => get_image_key(),
215            #[cfg(feature = "webgl")]
216            RenderingContext::WebGL2(..) => get_image_key(),
217            #[cfg(feature = "webgpu")]
218            RenderingContext::WebGPU(..) => get_image_key(),
219        };
220        self.image_key.set(image_key);
221        if let Some(image_key) = image_key {
222            rendering_context.set_image_key(image_key);
223        }
224    }
225
226    /// <https://html.spec.whatwg.org/multipage/#2d-context-creation-algorithm>
227    fn get_or_init_2d_context(
228        &self,
229        cx: &mut js::context::JSContext,
230        options: HandleValue,
231    ) -> Option<DomRoot<CanvasRenderingContext2D>> {
232        if let Some(ctx) = self.context() {
233            return match *ctx {
234                RenderingContext::Context2d(ref ctx) => Some(DomRoot::from_ref(ctx)),
235                _ => None,
236            };
237        }
238
239        let window = self.owner_window();
240        let size = self.get_size();
241
242        // Step 1. Let settings be the result of converting options to the dictionary type
243        // CanvasRenderingContext2DSettings. (This can throw an exception.)
244        let settings = match CanvasRenderingContext2DSettings::new(cx, options) {
245            Ok(ConversionResult::Success(settings)) => settings,
246            Ok(ConversionResult::Failure(error)) => {
247                throw_type_error(cx, &error);
248                return None;
249            },
250            Err(()) => return None,
251        };
252        let context =
253            CanvasRenderingContext2D::new(cx, window.as_global_scope(), self, size, &settings)?;
254        self.set_rendering_context(cx.no_gc(), || {
255            RenderingContext::Context2d(Dom::from_ref(&*context))
256        });
257        Some(context)
258    }
259
260    /// <https://html.spec.whatwg.org/multipage/#canvas-context-bitmaprenderer>
261    fn get_or_init_bitmaprenderer_context(
262        &self,
263        cx: &mut js::context::JSContext,
264    ) -> Option<DomRoot<ImageBitmapRenderingContext>> {
265        // Return the same object as was returned the last time the method was
266        // invoked with this same first argument.
267        if let Some(ctx) = self.context() {
268            return match *ctx {
269                RenderingContext::BitmapRenderer(ref ctx) => Some(DomRoot::from_ref(ctx)),
270                _ => None,
271            };
272        }
273
274        // Step 1. Let context be the result of running the
275        // ImageBitmapRenderingContext creation algorithm given this and
276        // options.
277        let canvas =
278            RootedHTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(DomRoot::from_ref(self));
279
280        // Step 2. Set this's context mode to bitmaprenderer.
281        let context = ImageBitmapRenderingContext::new(cx, &self.owner_global(), &canvas);
282        self.set_rendering_context(cx.no_gc(), || {
283            RenderingContext::BitmapRenderer(Dom::from_ref(&*context))
284        });
285
286        // Step 3. Return context.
287        Some(context)
288    }
289
290    #[cfg(feature = "webgl")]
291    fn get_or_init_webgl_context(
292        &self,
293        cx: &mut js::context::JSContext,
294        options: HandleValue,
295    ) -> Option<DomRoot<WebGLRenderingContext>> {
296        if let Some(ctx) = self.context() {
297            return match *ctx {
298                RenderingContext::WebGL(ref ctx) => Some(DomRoot::from_ref(ctx)),
299                _ => None,
300            };
301        }
302        let window = self.owner_window();
303        let canvas =
304            RootedHTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(DomRoot::from_ref(self));
305        let size = self.get_size();
306        let attrs = Self::get_gl_attributes(cx, options)?;
307        let context =
308            WebGLRenderingContext::new(cx, &window, &canvas, WebGLVersion::WebGL1, size, attrs)?;
309        self.set_rendering_context(cx.no_gc(), || {
310            RenderingContext::WebGL(Dom::from_ref(&*context))
311        });
312        Some(context)
313    }
314
315    #[cfg(feature = "webgl")]
316    fn get_or_init_webgl2_context(
317        &self,
318        cx: &mut js::context::JSContext,
319        options: HandleValue,
320    ) -> Option<DomRoot<WebGL2RenderingContext>> {
321        if !WebGL2RenderingContext::is_webgl2_enabled(cx, self.global().reflector().get_jsobject())
322        {
323            return None;
324        }
325        if let Some(ctx) = self.context() {
326            return match *ctx {
327                RenderingContext::WebGL2(ref ctx) => Some(DomRoot::from_ref(ctx)),
328                _ => None,
329            };
330        }
331        let window = self.owner_window();
332        let canvas =
333            RootedHTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(DomRoot::from_ref(self));
334        let size = self.get_size();
335        let attrs = Self::get_gl_attributes(cx, options)?;
336        let context = WebGL2RenderingContext::new(cx, &window, &canvas, size, attrs)?;
337        self.set_rendering_context(cx.no_gc(), || {
338            RenderingContext::WebGL2(Dom::from_ref(&*context))
339        });
340        Some(context)
341    }
342
343    #[cfg(feature = "webgpu")]
344    fn get_or_init_webgpu_context(
345        &self,
346        cx: &mut js::context::JSContext,
347    ) -> Option<DomRoot<GPUCanvasContext>> {
348        use servo_base::generic_channel;
349
350        if let Some(ctx) = self.context() {
351            return match *ctx {
352                RenderingContext::WebGPU(ref ctx) => Some(DomRoot::from_ref(ctx)),
353                _ => None,
354            };
355        }
356        let (sender, receiver) = generic_channel::channel().unwrap();
357        let global_scope = self.owner_global();
358        let _ = global_scope
359            .script_to_constellation_chan()
360            .send(ScriptToConstellationMessage::GetWebGPUChan(sender));
361        receiver
362            .recv()
363            .expect("Failed to get WebGPU channel")
364            .map(|channel| {
365                let context = GPUCanvasContext::new(cx, &global_scope, self, channel);
366                self.set_rendering_context(cx.no_gc(), || {
367                    RenderingContext::WebGPU(Dom::from_ref(&*context))
368                });
369                context
370            })
371    }
372
373    #[cfg(feature = "webgl")]
374    fn get_gl_attributes(
375        cx: &mut js::context::JSContext,
376        options: HandleValue,
377    ) -> Option<GLContextAttributes> {
378        match WebGLContextAttributes::new(cx, options) {
379            Ok(ConversionResult::Success(attrs)) => Some(attrs.convert()),
380            Ok(ConversionResult::Failure(error)) => {
381                throw_type_error(cx, &error);
382                None
383            },
384            _ => {
385                debug!("Unexpected error on conversion of WebGLContextAttributes");
386                None
387            },
388        }
389    }
390
391    pub(crate) fn is_valid(&self) -> bool {
392        self.Height() != 0 && self.Width() != 0
393    }
394
395    pub(crate) fn get_image_data(&self) -> Option<Snapshot> {
396        match self.context_mode.borrow().as_ref() {
397            Some(context) => context.get_image_data(),
398            None => {
399                let size = self.get_size();
400                if size.is_empty() ||
401                    pixels::compute_rgba8_byte_length_if_within_limit(
402                        size.width as usize,
403                        size.height as usize,
404                    )
405                    .is_none()
406                {
407                    None
408                } else {
409                    Some(Snapshot::cleared(size.cast()))
410                }
411            },
412        }
413    }
414
415    fn maybe_quality(quality: HandleValue) -> Option<f64> {
416        if quality.is_number() {
417            Some(quality.to_number())
418        } else {
419            None
420        }
421    }
422
423    pub(crate) fn update_rendering(&self, epoch: Epoch) -> Option<ImageKey> {
424        let context = self.context()?;
425        let image_key = self.image_key.get()?;
426        let pending = match &*context {
427            RenderingContext::Placeholder(..) => false,
428            RenderingContext::Context2d(context) => context.update_rendering(epoch),
429            RenderingContext::BitmapRenderer(context) => context.update_rendering(epoch),
430            #[cfg(feature = "webgl")]
431            RenderingContext::WebGL(context) => context.update_rendering(epoch),
432            #[cfg(feature = "webgl")]
433            RenderingContext::WebGL2(context) => context.base_context().update_rendering(epoch),
434            #[cfg(feature = "webgpu")]
435            RenderingContext::WebGPU(context) => context.update_rendering(epoch),
436        };
437
438        if pending {
439            return Some(image_key);
440        }
441        None
442    }
443}
444
445impl HTMLCanvasElementMethods<crate::DomTypeHolder> for HTMLCanvasElement {
446    // https://html.spec.whatwg.org/multipage/#dom-canvas-width
447    make_uint_getter!(Width, "width", DEFAULT_WIDTH);
448
449    /// <https://html.spec.whatwg.org/multipage/#dom-canvas-width>
450    fn SetWidth(&self, cx: &mut js::context::JSContext, value: u32) -> Fallible<()> {
451        // > When setting the value of the width or height attribute, if the context mode of the canvas element
452        // > is set to placeholder, the user agent must throw an "InvalidStateError" DOMException and leave the
453        // > attribute's value unchanged.
454        if let Some(RenderingContext::Placeholder(_)) = *self.context_mode.borrow() {
455            return Err(Error::InvalidState(Some(
456                "Canvas element's context mode is set to placeholder: Cannot set width".into(),
457            )));
458        }
459
460        let value = if value > UNSIGNED_LONG_MAX {
461            DEFAULT_WIDTH
462        } else {
463            value
464        };
465        self.upcast::<Element>()
466            .set_attribute(cx, &html5ever::local_name!("width"), value.into());
467        Ok(())
468    }
469
470    // https://html.spec.whatwg.org/multipage/#dom-canvas-height
471    make_uint_getter!(Height, "height", DEFAULT_HEIGHT);
472
473    /// <https://html.spec.whatwg.org/multipage/#dom-canvas-height>
474    fn SetHeight(&self, cx: &mut js::context::JSContext, value: u32) -> Fallible<()> {
475        // > When setting the value of the width or height attribute, if the context mode of the canvas element
476        // > is set to placeholder, the user agent must throw an "InvalidStateError" DOMException and leave the
477        // > attribute's value unchanged.
478        if let Some(RenderingContext::Placeholder(_)) = *self.context_mode.borrow() {
479            return Err(Error::InvalidState(Some(
480                "Canvas element's context mode is set to placeholder: Cannot set height".into(),
481            )));
482        }
483
484        let value = if value > UNSIGNED_LONG_MAX {
485            DEFAULT_HEIGHT
486        } else {
487            value
488        };
489        self.upcast::<Element>()
490            .set_attribute(cx, &html5ever::local_name!("height"), value.into());
491        Ok(())
492    }
493
494    /// <https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext>
495    fn GetContext(
496        &self,
497        cx: &mut js::context::JSContext,
498        id: DOMString,
499        options: HandleValue,
500    ) -> Fallible<Option<RootedRenderingContext>> {
501        // Step 1. If options is not an object, then set options to null.
502        let options = if options.get().is_object() {
503            options
504        } else {
505            HandleValue::null()
506        };
507
508        // Always throw an InvalidState exception when the canvas is in Placeholder mode (See table in the spec).
509        if let Some(RenderingContext::Placeholder(_)) = *self.context_mode.borrow() {
510            return Err(Error::InvalidState(Some(
511                "Canvas element's context mode is set to placeholder: Cannot get context".into(),
512            )));
513        }
514
515        Ok(match &*id.str() {
516            "2d" => self
517                .get_or_init_2d_context(cx, options)
518                .map(RootedRenderingContext::CanvasRenderingContext2D),
519            "bitmaprenderer" => self
520                .get_or_init_bitmaprenderer_context(cx)
521                .map(RootedRenderingContext::ImageBitmapRenderingContext),
522            #[cfg(feature = "webgl")]
523            "webgl" | "experimental-webgl" => self
524                .get_or_init_webgl_context(cx, options)
525                .map(RootedRenderingContext::WebGLRenderingContext),
526            #[cfg(feature = "webgl")]
527            "webgl2" | "experimental-webgl2" => self
528                .get_or_init_webgl2_context(cx, options)
529                .map(RootedRenderingContext::WebGL2RenderingContext),
530            #[cfg(feature = "webgpu")]
531            "webgpu" => self
532                .get_or_init_webgpu_context(cx)
533                .map(RootedRenderingContext::GPUCanvasContext),
534            _ => None,
535        })
536    }
537
538    /// <https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl>
539    fn ToDataURL(&self, mime_type: DOMString, quality: HandleValue) -> Fallible<USVString> {
540        // Step 1: If this canvas element's bitmap's origin-clean flag is set to false,
541        // then throw a "SecurityError" DOMException.
542        if !self.origin_is_clean() {
543            return Err(Error::Security(Some("Canvas bitmap is not clean".into())));
544        }
545
546        // Step 2: If this canvas element's bitmap has no pixels (i.e. either its
547        // horizontal dimension or its vertical dimension is zero), then return the string
548        // "data:,". (This is the shortest data: URL; it represents the empty string in a
549        // text/plain resource.)
550        if self.Width() == 0 || self.Height() == 0 {
551            return Ok(USVString("data:,".into()));
552        }
553
554        // Step 3: Let file be a serialization of this canvas element's bitmap as a file,
555        // passing type and quality if given.
556        let Some(mut snapshot) = self.get_image_data() else {
557            return Ok(USVString("data:,".into()));
558        };
559
560        let image_type = EncodedImageType::from(&mime_type.str() as &str);
561
562        let mut url = format!("data:{};base64,", image_type.as_mime_type());
563
564        let mut encoder = base64::write::EncoderStringWriter::from_consumer(
565            &mut url,
566            &base64::engine::general_purpose::STANDARD,
567        );
568
569        if snapshot
570            .encode_for_mime_type(&image_type, Self::maybe_quality(quality), &mut encoder)
571            .is_err()
572        {
573            // Step 4. If file is null, then return "data:,".
574            return Ok(USVString("data:,".into()));
575        }
576
577        // Step 5. Return a data: URL representing file. [RFC2397]
578        encoder.into_inner();
579        Ok(USVString(url))
580    }
581
582    /// <https://html.spec.whatwg.org/multipage/#dom-canvas-toblob>
583    fn ToBlob(
584        &self,
585        callback: RootedCallback<BlobCallback>,
586        mime_type: DOMString,
587        quality: HandleValue,
588    ) -> Fallible<()> {
589        // Step 1.
590        // If this canvas element's bitmap's origin-clean flag is set to false, then throw a
591        // "SecurityError" DOMException.
592        if !self.origin_is_clean() {
593            return Err(Error::Security(Some("Canvas bitmap is not clean".into())));
594        }
595
596        // Step 2. Let result be null.
597        // Step 3. If this canvas element's bitmap has pixels (i.e., neither its horizontal dimension
598        // nor its vertical dimension is zero),
599        // then set result to a copy of this canvas element's bitmap.
600        let result = if self.Width() == 0 || self.Height() == 0 {
601            None
602        } else {
603            self.get_image_data()
604        };
605
606        let this = Trusted::new(self);
607        let callback_id = self.callback_id.get().wrapping_add(1);
608        self.callback_id.set(callback_id);
609
610        self.blob_callbacks
611            .borrow_mut()
612            .insert(callback_id, callback.to_traced());
613        let quality = Self::maybe_quality(quality);
614        let image_type = EncodedImageType::from(&mime_type.str() as &str);
615
616        self.global()
617            .task_manager()
618            .canvas_blob_task_source()
619            .queue(task!(to_blob: move |cx| {
620                let this = this.root();
621                let Some(callback) = &this.blob_callbacks.safe_borrow_mut(cx.no_gc()).remove(&callback_id) else {
622                    return error!("Expected blob callback, but found none!");
623                };
624
625                let Some(mut snapshot) = result else {
626                    let _ = callback.Call__(cx, None, ExceptionHandling::Report);
627                    return;
628                };
629
630                // Step 4.1: If result is non-null, then set result to a serialization of
631                // result as a file with type and quality if given.
632                // Step 4.2: Queue an element task on the canvas blob serialization task
633                // source given the canvas element to run these steps:
634                let mut encoded: Vec<u8> = vec![];
635                let blob_impl;
636                let blob;
637                let result = match snapshot.encode_for_mime_type(&image_type, quality, &mut encoded) {
638                   Ok(..) => {
639                       // Step 4.2.1: If result is non-null, then set result to a new Blob
640                       // object, created in the relevant realm of this canvas element,
641                       // representing result. [FILEAPI]
642                       blob_impl = BlobImpl::new_from_bytes(encoded, image_type.as_mime_type().to_owned());
643                       blob = Blob::new(cx, &this.global(), blob_impl);
644                       Some(&*blob)
645                   }
646                   Err(..) => None,
647                };
648
649                // Step 4.2.2: Invoke callback with « result » and "report".
650                let _ = callback.Call__(cx, result, ExceptionHandling::Report);
651            }));
652
653        Ok(())
654    }
655
656    /// <https://html.spec.whatwg.org/multipage/#dom-canvas-transfercontroltooffscreen>
657    fn TransferControlToOffscreen(
658        &self,
659        cx: &mut js::context::JSContext,
660    ) -> Fallible<DomRoot<OffscreenCanvas>> {
661        if self.context_mode.borrow().is_some() {
662            // Step 1.
663            // If this canvas element's context mode is not set to none, throw an "InvalidStateError" DOMException.
664            return Err(Error::InvalidState(Some("Canvas element's context mode must not be set when transferring control to an offscreen canvas".into())));
665        };
666
667        // Step 2.
668        // Let offscreenCanvas be a new OffscreenCanvas object with its width and height equal to the values of
669        // the width and height content attributes of this canvas element.
670        // Step 3.
671        // Set the placeholder canvas element of offscreenCanvas to a weak reference to this canvas element.
672        let offscreen_canvas = OffscreenCanvas::new(
673            cx,
674            &self.global(),
675            None,
676            self.Width().into(),
677            self.Height().into(),
678            Some(WeakRef::new(self)),
679        );
680
681        // Step 4. Set this canvas element's context mode to placeholder.
682        self.set_rendering_context(cx.no_gc(), || {
683            RenderingContext::Placeholder(offscreen_canvas.as_traced())
684        });
685
686        // Step 5. Return offscreenCanvas.
687        Ok(offscreen_canvas)
688    }
689
690    /// <https://w3c.github.io/mediacapture-fromelement/#dom-htmlcanvaselement-capturestream>
691    fn CaptureStream(
692        &self,
693        cx: &mut js::context::JSContext,
694        _frame_request_rate: Option<Finite<f64>>,
695    ) -> DomRoot<MediaStream> {
696        let global = self.global();
697        let stream = MediaStream::new(cx, &global);
698        let track =
699            MediaStreamTrack::new(cx, &global, MediaStreamId::new(), MediaStreamType::Video);
700        stream.AddTrack(&track);
701        stream
702    }
703}
704
705impl VirtualMethods for HTMLCanvasElement {
706    fn super_type(&self) -> Option<&dyn VirtualMethods> {
707        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
708    }
709
710    fn attribute_mutated(
711        &self,
712        cx: &mut js::context::JSContext,
713        attr: AttrRef<'_>,
714        mutation: AttributeMutation,
715    ) {
716        self.super_type()
717            .unwrap()
718            .attribute_mutated(cx, attr, mutation);
719        match attr.local_name() {
720            &local_name!("width") | &local_name!("height") => {
721                self.recreate_contexts_after_resize();
722                self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
723            },
724            _ => {},
725        };
726    }
727
728    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
729        match attr.local_name() {
730            &local_name!("width") | &local_name!("height") => true,
731            _ => self
732                .super_type()
733                .unwrap()
734                .attribute_affects_presentational_hints(attr),
735        }
736    }
737
738    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
739        match *name {
740            local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
741            local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
742            _ => self
743                .super_type()
744                .unwrap()
745                .parse_plain_attribute(name, value),
746        }
747    }
748}
749
750#[cfg(feature = "webgl")]
751impl Convert<GLContextAttributes> for WebGLContextAttributes {
752    fn convert(self) -> GLContextAttributes {
753        GLContextAttributes {
754            alpha: self.alpha,
755            depth: self.depth,
756            stencil: self.stencil,
757            antialias: self.antialias,
758            premultiplied_alpha: self.premultipliedAlpha,
759            preserve_drawing_buffer: self.preserveDrawingBuffer,
760        }
761    }
762}