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