Skip to content

Truly independent web browser

LibWeb: Implement ImageBitmapRenderingContext

sideshowbarker88d62403be13
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index 4f4ca8d4cbf..134cb915a57 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -20,6 +20,7 @@ use liburl_rust::FfiOrigin;
use super::broadcast_channel::{BROADCAST_CHANNEL_MESSAGE_CLASS, BroadcastChannel, BroadcastChannelMessage};
use super::image_bitmap::ImageBitmap;
+use super::image_bitmap_rendering_context::ImageBitmapRenderingContext;
use super::image_data::ImageData;
use super::message_port::MessagePort;
use super::storage::{Storage, StorageType};
@@ -31,8 +32,9 @@ use crate::bindings::conversions::UsvString;
use crate::bindings::cpp_cell::CppCell;
use crate::bindings::environment_settings_object::relevant_settings_object;
use crate::bindings::event_target::CppEventTarget;
-use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments, wrap};
+use crate::bindings::interface::{Interface, Ref, allocate, cell_from_abi, cell_into_abi, realm_arguments, wrap};
use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};
+use crate::canvas_2d::canvas::Canvas;
use crate::dom::event::EventInit;
use crate::html::port_channel::give_up_on_parked_end;
use crate::html::structured_serialize::cpp::SerializedTransferRecord;
@@ -671,3 +673,65 @@ pub unsafe extern "C" fn web_rust_structured_clone(
let result = structured_clone(&cx, value, &transfer.values());
RawNativeFunctionResult::from_completion(result.map_err(|exception| exception.throw(&cx)))
}
+
+/// Creates the ImageBitmapRenderingContext of the HTMLCanvasElement whose cell is `canvas` and whose
+/// Web::HTML::CanvasHost is `canvas_host`, and returns its cell.
+///
+/// # Safety
+///
+/// `canvas` must be the live cell of the canvas, and `canvas_host` the same object as a Web::HTML::CanvasHost.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_bitmap_rendering_context_create(
+ vm: &Vm,
+ canvas: *mut c_void,
+ canvas_host: *mut c_void,
+ alpha: bool,
+) -> *mut c_void {
+ let canvas = Canvas {
+ cell: NonNull::new(canvas).expect("C++ passes the canvas"),
+ host: NonNull::new(canvas_host).expect("C++ passes the canvas"),
+ is_offscreen: false,
+ };
+ cell_into_abi(allocate(vm, |defer_gc| {
+ ImageBitmapRenderingContext::new(defer_gc, canvas, alpha)
+ }))
+}
+
+/// The Gfx::DecodedImageFrame of the output bitmap of the context, which stays valid until the output bitmap changes,
+/// or null for none.
+///
+/// # Safety
+///
+/// `context` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_bitmap_rendering_context_frame(context: *mut c_void) -> *const c_void {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageBitmapRenderingContext>(context) }.raw_frame()
+}
+
+/// # Safety
+///
+/// `context` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_bitmap_rendering_context_is_blank(context: *mut c_void) -> bool {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageBitmapRenderingContext>(context) }.is_blank()
+}
+
+/// # Safety
+///
+/// `context` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_bitmap_rendering_context_origin_clean(context: *mut c_void) -> bool {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageBitmapRenderingContext>(context) }.origin_clean()
+}
+
+/// # Safety
+///
+/// `context` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_bitmap_rendering_context_alpha(context: *mut c_void) -> bool {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageBitmapRenderingContext>(context) }.alpha()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap_rendering_context.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap_rendering_context.rs
new file mode 100644
index 00000000000..d605cf3a9e1
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap_rendering_context.rs
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#the-imagebitmaprenderingcontext-interface
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libgfx_rust::image_frame::ImageFrameHandle;
+use libjs_rust::api::{DeferGc, ForeignCellSlot, Gc, Realm, Trace};
+
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Ref, Wrappable};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::canvas_2d::canvas::Canvas;
+use crate::html::image_bitmap::ImageBitmap;
+
+unsafe extern "C" {
+ fn web_image_bitmap_frame_size_in_bytes(frame: *const c_void) -> usize;
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#concept-imagebitmaprenderingcontext-bitmap-mode
+enum BitmapMode {
+ /// The output bitmap is a default transparent bitmap, of the size of the canvas.
+ Blank,
+ /// The output bitmap refers to bitmap data that was acquired via transferFromImageBitmap() — none, for an
+ /// ImageBitmap that was created without any.
+ Valid(Option<ImageFrameHandle>),
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ImageBitmapRenderingContext {
+ canvas_cell: ForeignCellSlot,
+ #[gc(untraced)]
+ canvas: Canvas,
+ #[gc(untraced)]
+ bitmap_mode: RefCell<BitmapMode>,
+ /// The origin-clean flag of the output bitmap,
+ /// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean
+ #[gc(untraced)]
+ origin_clean: Cell<bool>,
+ /// https://html.spec.whatwg.org/multipage/canvas.html#concept-imagebitmaprenderingcontext-alpha
+ #[gc(untraced)]
+ alpha: bool,
+}
+
+impl Wrappable for ImageBitmapRenderingContext {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ self.canvas.relevant_realm()
+ }
+
+ const OWNS_EXTERNAL_MEMORY: bool = true;
+
+ fn external_memory_size(&self) -> usize {
+ // NB: LibGC asks while it sweeps, when nothing borrows the bitmap mode mutably.
+ match self.bitmap_mode.try_borrow().as_deref() {
+ // SAFETY: The frame is live for as long as the context holds it.
+ Ok(BitmapMode::Valid(Some(frame))) => unsafe { web_image_bitmap_frame_size_in_bytes(frame.as_raw()) },
+ _ => 0,
+ }
+ }
+}
+
+impl ImageBitmapRenderingContext {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#imagebitmaprenderingcontext-creation-algorithm
+ pub(crate) fn new(_: &DeferGc<'_>, canvas: Canvas, alpha: bool) -> Self {
+ // 1. Let settings be the result of converting options to the dictionary type ImageBitmapRenderingContextSettings.
+ // (This can throw an exception.)
+ // NB: HTMLCanvasElement::get_context() converts the options, and passes alpha.
+
+ // 2. Let context be a new ImageBitmapRenderingContext object.
+ // 3. Initialize context's canvas attribute to point to target.
+ let canvas_cell = ForeignCellSlot::empty();
+ // SAFETY: The canvas is a live cell of the heap that the runtime allocates from.
+ unsafe { canvas_cell.set(Some(canvas.cell)) };
+
+ // 4. Set context's output bitmap to the same bitmap as target's bitmap (so that they are shared).
+ // 5. Run the steps to set an ImageBitmapRenderingContext's output bitmap with context.
+ // 6. Initialize context's alpha flag to true.
+ // 7. Process each of the members of settings as follows:
+ // alpha: If false, then set context's alpha flag to false.
+ // 8. Return context.
+ Self {
+ canvas_cell,
+ canvas,
+ bitmap_mode: RefCell::new(BitmapMode::Blank),
+ origin_clean: Cell::new(true),
+ alpha,
+ }
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-imagebitmaprenderingcontext-canvas
+ pub(crate) fn canvas(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // The canvas attribute must return the value it was initialized to when the object was created.
+ Ok(self.canvas.wrapper(cx.realm()))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-imagebitmaprenderingcontext-transferfromimagebitmap
+ pub(crate) fn transfer_from_image_bitmap(
+ &self,
+ _: &mut CallContext,
+ bitmap: Option<Ref<ImageBitmap>>,
+ ) -> WebIdlResult<()> {
+ // 1. Let bitmapContext be the ImageBitmapRenderingContext object on which the transferFromImageBitmap() method
+ // was called.
+ // 2. If bitmap is null, then run the steps to set an ImageBitmapRenderingContext's output bitmap, with
+ // bitmapContext as the context argument and no bitmap argument, then return.
+ let Some(bitmap) = bitmap else {
+ self.set_output_bitmap(None);
+ return Ok(());
+ };
+
+ // 3. If the value of bitmap's [[Detached]] internal slot is set to true, then throw an "InvalidStateError"
+ // DOMException.
+ if bitmap.is_detached() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_utf8("The ImageBitmap is detached"),
+ ));
+ }
+
+ // 4. Run the steps to set an ImageBitmapRenderingContext's output bitmap, with the context argument equal to
+ // bitmapContext, and the bitmap argument referring to bitmap's underlying bitmap data.
+ self.set_output_bitmap(Some((bitmap.frame(), bitmap.origin_clean())));
+
+ // 5. Set the value of bitmap's [[Detached]] internal slot to true.
+ // 6. Unset bitmap's bitmap data.
+ bitmap.close_bitmap();
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#set-an-imagebitmaprenderingcontext's-output-bitmap
+ fn set_output_bitmap(&self, bitmap: Option<(Option<ImageFrameHandle>, bool)>) {
+ match bitmap {
+ // 1. If a bitmap argument was not provided:
+ None => {
+ // 1. Set context's bitmap mode to blank.
+ // 2. Let canvas be the canvas element to which context is bound.
+ // 3. Set context's output bitmap to be transparent black with a natural width equal to the numeric
+ // value of canvas's width attribute and a natural height equal to the numeric value of canvas's
+ // height attribute, those values being interpreted in CSS pixels.
+ // NB: The canvas makes that bitmap when something reads it, at the size its attributes have then.
+ self.bitmap_mode.replace(BitmapMode::Blank);
+
+ // 4. Set the output bitmap's origin-clean flag to true.
+ self.origin_clean.set(true);
+ }
+ // 2. If a bitmap argument was provided:
+ Some((frame, origin_clean)) => {
+ // 1. Set context's bitmap mode to valid.
+ // 2. Set context's output bitmap to refer to the same underlying bitmap data as bitmap, without making
+ // a copy.
+ // The origin-clean flag of bitmap is included in the bitmap data to be referenced by context's
+ // output bitmap.
+ self.bitmap_mode.replace(BitmapMode::Valid(frame));
+ self.origin_clean.set(origin_clean);
+ }
+ }
+ self.canvas.did_change_content();
+ }
+
+ /// The frame of the output bitmap, which stays valid until the output bitmap changes; null in blank mode, and for
+ /// an output bitmap without bitmap data.
+ pub(crate) fn raw_frame(&self) -> *const c_void {
+ match &*self.bitmap_mode.borrow() {
+ BitmapMode::Valid(Some(frame)) => frame.as_raw(),
+ _ => core::ptr::null(),
+ }
+ }
+
+ /// Whether the bitmap mode is blank.
+ pub(crate) fn is_blank(&self) -> bool {
+ matches!(*self.bitmap_mode.borrow(), BitmapMode::Blank)
+ }
+
+ pub(crate) fn origin_clean(&self) -> bool {
+ self.origin_clean.get()
+ }
+
+ pub(crate) fn alpha(&self) -> bool {
+ self.alpha
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index a4f7015cfb3..c90d775bc1c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -59,6 +59,8 @@ pub(crate) mod exports;
#[cfg(not(test))]
pub(crate) mod image_bitmap;
#[cfg(not(test))]
+pub(crate) mod image_bitmap_rendering_context;
+#[cfg(not(test))]
pub(crate) mod image_data;
#[cfg(not(test))]
pub(crate) mod message_channel;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 840cd575857..8bc3852c701 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -511,6 +511,7 @@ set(SOURCES
HTML/HTMLVideoElement.cpp
HTML/HyperlinkElementUtils.cpp
HTML/ImageBitmap.cpp
+ HTML/ImageBitmapRenderingContext.cpp
HTML/ImageData.cpp
HTML/ImageRequest.cpp
HTML/ListOfAvailableImages.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 5636ec8ac75..0979a145e5a 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -784,6 +784,7 @@ class HTMLUListElement;
class HTMLUnknownElement;
class HTMLVideoElement;
class ImageBitmap;
+class ImageBitmapRenderingContext;
class ImageData;
class ImageRequest;
class ListOfAvailableImages;
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index 1cd457b4cf6..28100359ae6 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -51,6 +51,7 @@
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/HTMLVideoElement.h>
#include <LibWeb/HTML/ImageBitmap.h>
+#include <LibWeb/HTML/ImageBitmapRenderingContext.h>
#include <LibWeb/HTML/ImageRequest.h>
#include <LibWeb/HTML/OffscreenCanvas.h>
#include <LibWeb/HTML/OffscreenCanvasRenderingContext2D.h>
@@ -772,7 +773,11 @@ void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind
auto width = maybe_width.is_exception() ? 0 : maybe_width.release_value();
auto height = maybe_height.is_exception() ? 0 : maybe_height.release_value();
- return { width, height }; }, [](GC::Ref<HTMLCanvasElement> source) -> Gfx::IntSize { return { source->width(), source->height() }; }, [](GC::Ref<OffscreenCanvas> source) -> Gfx::IntSize { return source->bitmap_size_for_canvas(); }, [](GC::Ref<HTMLVideoElement> source) -> Gfx::IntSize { return { source->video_width(), source->video_height() }; }, [](GC::Ref<ImageBitmap>) -> Gfx::IntSize { VERIFY_NOT_REACHED(); });
+ return { width, height }; }, [](GC::Ref<HTMLCanvasElement> source) -> Gfx::IntSize {
+ // NB: A valid output bitmap of an ImageBitmapRenderingContext has the dimensions of its bitmap data.
+ if (auto const* bitmap_renderer = source->canvas_bitmap_renderer_context(); bitmap_renderer && !bitmap_renderer->is_blank())
+ return source->bitmap_size_for_canvas();
+ return { source->width(), source->height() }; }, [](GC::Ref<OffscreenCanvas> source) -> Gfx::IntSize { return source->bitmap_size_for_canvas(); }, [](GC::Ref<HTMLVideoElement> source) -> Gfx::IntSize { return { source->video_width(), source->video_height() }; }, [](GC::Ref<ImageBitmap>) -> Gfx::IntSize { VERIFY_NOT_REACHED(); });
*out_width = size.width();
*out_height = size.height();
}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
index 10027e48520..c6ab08c97ce 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
@@ -9,6 +9,7 @@
#include <LibWeb/HTML/DecodedImageData.h>
#include <LibWeb/HTML/HTMLMediaElement.h>
#include <LibWeb/HTML/ImageBitmap.h>
+#include <LibWeb/HTML/ImageBitmapRenderingContext.h>
#include <LibWeb/HTML/ImageRequest.h>
#include <LibWeb/Layout/ImageProvider.h>
@@ -73,7 +74,12 @@ WebIDL::ExceptionOr<CanvasImageSourceUsability> check_usability_of_image(CanvasI
// HTMLCanvasElement
[](GC::Ref<HTMLCanvasElement> canvas_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
// If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.
- if (canvas_element->width() == 0 || canvas_element->height() == 0)
+ // NB: A valid output bitmap of an ImageBitmapRenderingContext has the dimensions of its bitmap data.
+ auto const* bitmap_renderer = canvas_element->canvas_bitmap_renderer_context();
+ auto const has_zero_dimension = bitmap_renderer && !bitmap_renderer->is_blank()
+ ? canvas_element->bitmap_size_for_canvas().is_empty()
+ : canvas_element->width() == 0 || canvas_element->height() == 0;
+ if (has_zero_dimension)
return WebIDL::InvalidStateError::create("Canvas width or height is zero"_utf16);
return Optional<CanvasImageSourceUsability> {};
},
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp
index 1bc3caa3092..0d8e10e863d 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp
@@ -12,6 +12,7 @@
#include <LibWeb/HTML/Canvas/CanvasHost.h>
#include <LibWeb/HTML/Canvas/PredefinedColorSpace.h>
#include <LibWeb/HTML/Canvas/SerializeBitmap.h>
+#include <LibWeb/HTML/ImageBitmapRenderingContext.h>
#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
namespace Web::HTML {
@@ -51,6 +52,16 @@ RefPtr<Gfx::Bitmap> CanvasHost::get_bitmap_from_surface()
if (size.is_empty())
return nullptr;
+ // NB: A blank output bitmap of an ImageBitmapRenderingContext is the transparent bitmap below.
+ if (auto* context = canvas_bitmap_renderer_context(); context && !context->is_blank()) {
+ // FIXME: Convert bitmap data that isn't in the sRGB color space.
+ if (auto const* frame = context->frame(); frame) {
+ if (auto bitmap = frame->bitmap().clone(); !bitmap.is_error())
+ return bitmap.release_value();
+ }
+ return nullptr;
+ }
+
if (auto* webgl_context = canvas_webgl_context())
return webgl_context->read_back_drawing_buffer({ {}, size });
@@ -66,6 +77,13 @@ RefPtr<Gfx::Bitmap> CanvasHost::get_bitmap_from_surface()
Optional<Gfx::DecodedImageFrame> CanvasHost::get_frame_from_surface()
{
+ // NB: The output bitmap of an ImageBitmapRenderingContext refers to its bitmap data, with its color space.
+ if (auto* context = canvas_bitmap_renderer_context(); context && !context->is_blank()) {
+ if (auto const* frame = context->frame())
+ return *frame;
+ return {};
+ }
+
if (auto* context = canvas_2d_context(); context && context->color_space() != Bindings::PredefinedColorSpace::Srgb) {
auto const size = bitmap_size_for_canvas();
if (size.is_empty())
@@ -98,6 +116,8 @@ bool CanvasHost::is_origin_clean() const
{
if (auto* context = canvas_2d_context())
return context->origin_clean();
+ if (auto* context = canvas_bitmap_renderer_context())
+ return context->origin_clean();
// NB: The texture uploads of a WebGL context throw a "SecurityError" DOMException for a source that is not
// origin-clean, so its bitmap stays origin-clean. A video is the exception, as long as its media data is
// never CORS-cross-origin (see image_is_not_origin_clean()).
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.h b/Libraries/LibWeb/HTML/Canvas/CanvasHost.h
index 01ea474446b..4c4be0ee219 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.h
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.h
@@ -26,6 +26,7 @@ public:
virtual Canvas2DContextBase* canvas_2d_context() const = 0;
virtual WebGL::WebGLRenderingContextBase* canvas_webgl_context() const = 0;
+ virtual ImageBitmapRenderingContext* canvas_bitmap_renderer_context() const { return nullptr; }
virtual Page& canvas_page() = 0;
virtual DOM::EventTarget& canvas_event_target() = 0;
diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp
index 0a445f630f0..1b59a62db5b 100644
--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp
@@ -11,6 +11,7 @@
#include <LibGfx/Bitmap.h>
#include <LibGfx/SharedImage.h>
#include <LibWeb/Bindings/CanvasRenderingContext2DSettings.h>
+#include <LibWeb/Bindings/ImageBitmapRenderingContextSettings.h>
#include <LibWeb/Bindings/WebGLRenderingContextBase.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
@@ -27,6 +28,7 @@
#include <LibWeb/HTML/Canvas/SerializeBitmap.h>
#include <LibWeb/HTML/CanvasRenderingContext2D.h>
#include <LibWeb/HTML/HTMLCanvasElement.h>
+#include <LibWeb/HTML/ImageBitmapRenderingContext.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/Numbers.h>
#include <LibWeb/HTML/OffscreenCanvas.h>
@@ -167,6 +169,9 @@ void HTMLCanvasElement::reset_context_to_default_state()
[](GC::Ref<WebGL::WebGL2RenderingContext>& context) {
context->reset_to_default_state();
},
+ [](GC::Ref<ImageBitmapRenderingContext>&) {
+ // NB: An ImageBitmapRenderingContext has no state to reset.
+ },
[](Empty) {
// Do nothing.
});
@@ -177,6 +182,13 @@ Canvas2DContextBase* HTMLCanvasElement::canvas_2d_context() const
return canvas_rendering_context_2d().ptr();
}
+ImageBitmapRenderingContext* HTMLCanvasElement::canvas_bitmap_renderer_context() const
+{
+ if (auto const* context = m_context.get_pointer<GC::Ref<ImageBitmapRenderingContext>>())
+ return context->ptr();
+ return nullptr;
+}
+
WebGL::WebGLRenderingContextBase* HTMLCanvasElement::canvas_webgl_context() const
{
return m_context.visit(
@@ -204,6 +216,14 @@ void HTMLCanvasElement::did_change_canvas_content()
{
set_canvas_content_dirty();
+ // NB: The output bitmap of an ImageBitmapRenderingContext reaches the Compositor in the paint facts of the canvas,
+ // so the display list has to record the canvas again.
+ if (canvas_bitmap_renderer_context()) {
+ Painting::push_canvas_paint_facts(*this);
+ set_needs_repaint(InvalidateDisplayList::PaintCommands);
+ return;
+ }
+
// NB: Don't request a display list recording here: the new content reaches the compositor through the canvas
// surface registry when the canvas is presented, and the cached DrawCanvas command is invalidated when the
// content generation moves in prepare_for_compositing.
@@ -281,6 +301,10 @@ void HTMLCanvasElement::notify_context_about_canvas_size_change()
[&](GC::Ref<WebGL::WebGL2RenderingContext>& context) {
context->set_size(bitmap_size_for_canvas());
},
+ [](GC::Ref<ImageBitmapRenderingContext>&) {
+ // NB: A blank output bitmap takes the size of the canvas when something reads it, and a valid one keeps
+ // the size of its bitmap data.
+ },
[](Empty) {
// Do nothing.
});
@@ -340,6 +364,16 @@ HTMLCanvasElement::HasOrCreatedContext HTMLCanvasElement::create_2d_context(Canv
return HasOrCreatedContext::Yes;
}
+HTMLCanvasElement::HasOrCreatedContext HTMLCanvasElement::create_bitmap_renderer_context(bool alpha)
+{
+ if (!m_context.has<Empty>())
+ return m_context.has<GC::Ref<ImageBitmapRenderingContext>>() ? HasOrCreatedContext::Yes : HasOrCreatedContext::No;
+
+ m_context = ImageBitmapRenderingContext::create(*this, alpha);
+ Painting::push_canvas_paint_facts(*this);
+ return HasOrCreatedContext::Yes;
+}
+
template<typename ContextType>
JS::ThrowCompletionOr<HTMLCanvasElement::HasOrCreatedContext> HTMLCanvasElement::create_webgl_context(JS::Value options)
{
@@ -389,11 +423,25 @@ JS::ThrowCompletionOr<HTMLCanvasElement::RenderingContext> HTMLCanvasElement::ge
return Empty {};
}
+ if (type == u"bitmaprenderer"sv) {
+ auto settings = TRY(Bindings::convert_to_idl_value_for_image_bitmap_rendering_context_settings(vm(), options));
+ if (create_bitmap_renderer_context(settings.alpha) == HasOrCreatedContext::Yes)
+ return m_context.get<GC::Ref<ImageBitmapRenderingContext>>();
+
+ return Empty {};
+ }
+
return Empty {};
}
Gfx::IntSize HTMLCanvasElement::bitmap_size_for_canvas() const
{
+ // NB: A valid output bitmap of an ImageBitmapRenderingContext keeps the size of its bitmap data.
+ if (auto* context = canvas_bitmap_renderer_context(); context && !context->is_blank()) {
+ if (auto const* frame = context->frame())
+ return { frame->width(), frame->height() };
+ return {};
+ }
return bitmap_size_for_dimensions(width(), height());
}
@@ -526,6 +574,9 @@ void HTMLCanvasElement::prepare_for_compositing()
[](GC::Ref<WebGL::WebGL2RenderingContext>& context) {
context->prepare_for_compositing();
},
+ [](GC::Ref<ImageBitmapRenderingContext>&) {
+ // NB: The output bitmap reaches the Compositor with the display list, as the paint facts of the canvas.
+ },
[](Empty) {
// Do nothing.
});
diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.h b/Libraries/LibWeb/HTML/HTMLCanvasElement.h
index f712af68f30..c3db0311e75 100644
--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.h
+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.h
@@ -25,7 +25,7 @@ class HTMLCanvasElement final
GC_DECLARE_ALLOCATOR(HTMLCanvasElement);
public:
- using RenderingContext = Variant<GC::Ref<CanvasRenderingContext2D>, GC::Ref<WebGL::WebGLRenderingContext>, GC::Ref<WebGL::WebGL2RenderingContext>, Empty>;
+ using RenderingContext = Variant<GC::Ref<CanvasRenderingContext2D>, GC::Ref<WebGL::WebGLRenderingContext>, GC::Ref<WebGL::WebGL2RenderingContext>, GC::Ref<ImageBitmapRenderingContext>, Empty>;
virtual ~HTMLCanvasElement() override;
@@ -33,6 +33,7 @@ public:
virtual Gfx::IntSize bitmap_size_for_canvas() const override;
virtual Canvas2DContextBase* canvas_2d_context() const override;
virtual WebGL::WebGLRenderingContextBase* canvas_webgl_context() const override;
+ virtual ImageBitmapRenderingContext* canvas_bitmap_renderer_context() const override;
virtual Page& canvas_page() override;
virtual DOM::EventTarget& canvas_event_target() override { return *this; }
virtual JS::Object& canvas_relevant_global_object() const override;
@@ -108,11 +109,12 @@ private:
template<typename ContextType>
JS::ThrowCompletionOr<HasOrCreatedContext> create_webgl_context(JS::Value options);
+ HasOrCreatedContext create_bitmap_renderer_context(bool alpha);
void reset_context_to_default_state();
void notify_context_about_canvas_size_change();
void did_commit_placeholder_frame(Gfx::IntSize, bool origin_clean);
- Variant<GC::Ref<HTML::CanvasRenderingContext2D>, GC::Ref<WebGL::WebGLRenderingContext>, GC::Ref<WebGL::WebGL2RenderingContext>, Empty> m_context;
+ Variant<GC::Ref<HTML::CanvasRenderingContext2D>, GC::Ref<WebGL::WebGLRenderingContext>, GC::Ref<WebGL::WebGL2RenderingContext>, GC::Ref<ImageBitmapRenderingContext>, Empty> m_context;
bool m_canvas_content_dirty { false };
u64 m_content_generation { 0 };
diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.idl b/Libraries/LibWeb/HTML/HTMLCanvasElement.idl
index c62337437fc..92174b15545 100644
--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.idl
+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.idl
@@ -1,5 +1,5 @@
-// FIXME: The RenderingContext union is missing ImageBitmapRenderingContext and GPUCanvasContext.
-typedef (CanvasRenderingContext2D or WebGLRenderingContext or WebGL2RenderingContext) RenderingContext;
+// FIXME: The RenderingContext union is missing GPUCanvasContext.
+typedef (CanvasRenderingContext2D or ImageBitmapRenderingContext or WebGLRenderingContext or WebGL2RenderingContext) RenderingContext;
// https://html.spec.whatwg.org/multipage/semantics.html#htmlcanvaselement
[Exposed=Window]
diff --git a/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.cpp b/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.cpp
new file mode 100644
index 00000000000..f1abb5848cc
--- /dev/null
+++ b/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGfx/DecodedImageFrame.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/HTML/HTMLCanvasElement.h>
+#include <LibWeb/HTML/ImageBitmapRenderingContext.h>
+
+namespace Web::HTML {
+
+extern "C" {
+// Defined in Bindings/Rust/src/html/exports.rs.
+void* web_image_bitmap_rendering_context_create(JSVM*, void* canvas, void* canvas_host, bool alpha);
+Gfx::DecodedImageFrame const* web_image_bitmap_rendering_context_frame(void const* context);
+bool web_image_bitmap_rendering_context_is_blank(void const* context);
+bool web_image_bitmap_rendering_context_origin_clean(void const* context);
+bool web_image_bitmap_rendering_context_alpha(void const* context);
+}
+
+GC::Ref<ImageBitmapRenderingContext> ImageBitmapRenderingContext::create(HTMLCanvasElement& canvas, bool alpha)
+{
+ // NB: The canvas is a GC cell and a CanvasHost at different addresses, so Rust gets both.
+ GC::Cell& canvas_cell = canvas;
+ CanvasHost& canvas_host = canvas;
+ auto* context = web_image_bitmap_rendering_context_create(JS::HostABI::vm_to_abi(JS::VM::the()), &canvas_cell, &canvas_host, alpha);
+ return GC::Ref { *static_cast<ImageBitmapRenderingContext*>(context) };
+}
+
+Gfx::DecodedImageFrame const* ImageBitmapRenderingContext::frame() const
+{
+ return web_image_bitmap_rendering_context_frame(this);
+}
+
+bool ImageBitmapRenderingContext::is_blank() const
+{
+ return web_image_bitmap_rendering_context_is_blank(this);
+}
+
+bool ImageBitmapRenderingContext::origin_clean() const
+{
+ return web_image_bitmap_rendering_context_origin_clean(this);
+}
+
+bool ImageBitmapRenderingContext::alpha() const
+{
+ return web_image_bitmap_rendering_context_alpha(this);
+}
+
+}
diff --git a/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.h b/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.h
new file mode 100644
index 00000000000..25526e98fcd
--- /dev/null
+++ b/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibGfx/Forward.h>
+#include <LibWeb/Bindings/ImageBitmapRenderingContext.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::HTML {
+
+// https://html.spec.whatwg.org/multipage/canvas.html#the-imagebitmaprenderingcontext-interface
+// The C++ side of an ImageBitmapRenderingContext, which is implemented in Rust
+// (Libraries/LibWeb/Bindings/Rust/src/html): what HTMLCanvasElement creates, and what its painting and readback read.
+class WEB_API ImageBitmapRenderingContext final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(ImageBitmapRenderingContext, image_bitmap_rendering_context)
+
+public:
+ // https://html.spec.whatwg.org/multipage/canvas.html#imagebitmaprenderingcontext-creation-algorithm
+ static GC::Ref<ImageBitmapRenderingContext> create(HTMLCanvasElement&, bool alpha);
+
+ // The bitmap data of the output bitmap, which stays valid until the output bitmap changes; null in blank mode, and
+ // for an output bitmap without bitmap data.
+ Gfx::DecodedImageFrame const* frame() const;
+
+ // https://html.spec.whatwg.org/multipage/canvas.html#concept-imagebitmaprenderingcontext-bitmap-mode
+ bool is_blank() const;
+
+ // https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean
+ bool origin_clean() const;
+
+ // https://html.spec.whatwg.org/multipage/canvas.html#concept-imagebitmaprenderingcontext-alpha
+ bool alpha() const;
+};
+
+}
diff --git a/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.idl b/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.idl
new file mode 100644
index 00000000000..af53b796799
--- /dev/null
+++ b/Libraries/LibWeb/HTML/ImageBitmapRenderingContext.idl
@@ -0,0 +1,6 @@
+// https://html.spec.whatwg.org/multipage/canvas.html#the-imagebitmaprenderingcontext-interface
+[Exposed=(Window,Worker), ImplementedIn=Rust]
+interface ImageBitmapRenderingContext {
+ readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;
+ undefined transferFromImageBitmap(ImageBitmap? bitmap);
+};
diff --git a/Libraries/LibWeb/HTML/ImageBitmapRenderingContextSettings.idl b/Libraries/LibWeb/HTML/ImageBitmapRenderingContextSettings.idl
new file mode 100644
index 00000000000..2f78c3f10e8
--- /dev/null
+++ b/Libraries/LibWeb/HTML/ImageBitmapRenderingContextSettings.idl
@@ -0,0 +1,4 @@
+// https://html.spec.whatwg.org/multipage/canvas.html#imagebitmaprenderingcontextsettings
+dictionary ImageBitmapRenderingContextSettings {
+ boolean alpha = true;
+};
diff --git a/Libraries/LibWeb/Painting/PaintFacts.cpp b/Libraries/LibWeb/Painting/PaintFacts.cpp
index e5d5bbeeb70..de18f882f1a 100644
--- a/Libraries/LibWeb/Painting/PaintFacts.cpp
+++ b/Libraries/LibWeb/Painting/PaintFacts.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLMapElement.h>
#include <LibWeb/HTML/HTMLVideoElement.h>
+#include <LibWeb/HTML/ImageBitmapRenderingContext.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/NavigableContainer.h>
#include <LibWeb/HTML/RemoteNavigable.h>
@@ -62,6 +63,19 @@ void push_form_control_paint_facts(HTML::HTMLInputElement& input)
static void queue_canvas_paint_facts(HTML::HTMLCanvasElement const& canvas)
{
+ // NB: The output bitmap of an ImageBitmapRenderingContext is painted as the image of the canvas.
+ if (auto const* bitmap_renderer = canvas.canvas_bitmap_renderer_context()) {
+ Layout::RustFFI::FfiReplacedImagePaintFacts image_facts {};
+ if (auto const* frame = bitmap_renderer->frame()) {
+ image_facts.content.kind = Layout::RustFFI::FfiImageContentKind::Raster;
+ image_facts.content.frame = frame;
+ }
+ queue_element_paint_facts(canvas, [&](auto* host, u32 element) {
+ Layout::RustFFI::render_state_set_element_image_paint_facts(host, element, image_facts);
+ });
+ return;
+ }
+
Layout::RustFFI::FfiCanvasPaintFacts facts {};
if (auto content_size = canvas.canvas_surface_content_size(); content_size.has_value()) {
facts.has_content = true;
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
index c95c3fe33e1..3e678ac9fbc 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
@@ -4501,7 +4501,8 @@ impl LayoutNodeArena {
/// Writes `facts` onto the box `target` names, and every row sharing its DOM node, where the box paints facts of
/// their kind. A box that owns the provider of its image shows that provider's image, which only facts naming the
- /// box by its row carry, and none before the host hands it the provider.
+ /// box by its row carry, and none before the host hands it the provider. A canvas whose context is an
+ /// ImageBitmapRenderingContext paints the output bitmap of the context as its image.
pub(crate) fn set_replaced_paint_facts(
&mut self,
target: super::tree_update_marks::MarkedBox,
@@ -4517,6 +4518,7 @@ impl LayoutNodeArena {
ReplacedPaintFacts::FormControl(_) => matches!(kind, NodeKind::CheckBox | NodeKind::RadioButton),
ReplacedPaintFacts::Canvas(_) => kind == NodeKind::CanvasBox,
ReplacedPaintFacts::NavigableContainer(_) => kind == NodeKind::NavigableContainerViewport,
+ ReplacedPaintFacts::Image(_) if kind == NodeKind::CanvasBox => true,
ReplacedPaintFacts::Image(_) => {
matches!(kind, NodeKind::ImageBox | NodeKind::SVGImageBox)
&& match self.owned_image_provider(id) {
diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/replaced.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/replaced.rs
index 4fd3dea7c92..71e109847a8 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/paint/replaced.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/replaced.rs
@@ -381,15 +381,38 @@ fn paint_custom_highlight_washes<O: Observer>(
}
pub(crate) fn paint_canvas_foreground<O: Observer>(recorder: &mut PaintRecorder<'_, O>, paintable: NodeSlotId) {
- let facts = recorder
- .source
- .replaced_paint_facts(paintable)
- .and_then(|facts| facts.canvas())
- .unwrap_or_default();
+ let replaced_facts = recorder.source.replaced_paint_facts(paintable);
let (_, image_rendering) = replaced_style(recorder, paintable);
let canvas_rect = recorder
.converter
.rounded_device_rect(absolute_rect(recorder.source, paintable));
+
+ // NB: A canvas whose context is an ImageBitmapRenderingContext paints the output bitmap of the context as its image.
+ // AD-HOC: The spec has the canvas take the natural dimensions of its output bitmap. Instead, the canvas keeps the
+ // natural dimensions its width and height attributes give it, and the output bitmap is stretched to fill
+ // its content box — so a transfer never changes the layout of the page.
+ // https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-element
+ // FIXME: Composite the output bitmap onto opaque black when the alpha flag of the context is false.
+ if let Some(image_facts) = replaced_facts.clone().and_then(|facts| facts.image()) {
+ if image_facts.content == crate::painting::image_content::ImageContent::None {
+ return;
+ }
+ let (content_rect, corner_radii) = replaced_content_clip_geometry(recorder, paintable);
+ let corner_clip =
+ corner_radii.map(|corner_radii| PendingInlineClip::intersecting_rounded_rect(content_rect, corner_radii));
+ recorder.record_with_inline_clips(corner_clip.as_slice(), |recorder| {
+ paint_replaced_image_content(
+ recorder,
+ paintable,
+ &image_facts.content,
+ canvas_rect.to_float(),
+ image_rendering,
+ );
+ });
+ return;
+ }
+
+ let facts = replaced_facts.and_then(|facts| facts.canvas()).unwrap_or_default();
if !facts.has_content {
return;
}
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 796de4816c2..77f05b31170 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -325,6 +325,8 @@ libweb_js_bindings(HTML/HTMLUnknownElement)
libweb_js_bindings(HTML/HTMLVideoElement)
libweb_js_bindings(HTML/HyperlinkElementUtils)
libweb_js_bindings(HTML/ImageBitmap)
+libweb_js_bindings(HTML/ImageBitmapRenderingContext)
+libweb_js_bindings(HTML/ImageBitmapRenderingContextSettings)
libweb_js_bindings(HTML/ImageData)
libweb_js_bindings(HTML/Location)
libweb_js_bindings(HTML/MediaError)
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-expected.html b/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-expected.html
new file mode 100644
index 00000000000..bababda44cd
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-expected.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<body>
+ <p>Test whether the imageOrientation "from-image" works when creating an ImageBitmap from the ImageData of a canvas, and then transfered to an ImageBitmapRenderingContext.</p>
+ <canvas id="canvas" width="300" height="300"></canvas>
+</body>
+<script>
+
+function drawSquares(ctx) {
+ ctx.fillStyle = 'red';
+ ctx.fillRect(0,0,150,150);
+ ctx.fillStyle = 'green';
+ ctx.fillRect(150,0,300,150);
+ ctx.fillStyle = 'blue';
+ ctx.fillRect(0,150,150,300);
+}
+
+async function runTest() {
+ const canvas = document.getElementById('canvas');
+ canvas.width = 300;
+ canvas.height = 300;
+ const ctx = canvas.getContext('2d');
+ drawSquares(ctx);
+}
+
+runTest();
+
+</script>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped-expected.html b/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped-expected.html
new file mode 100644
index 00000000000..5e216719736
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped-expected.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<body>
+ <p>Test whether the imageOrientation "flipY" works when creating an ImageBitmap from the ImageData of a canvas, and then transfered to an ImageBitmapRenderingContext.</p>
+ <canvas id="canvas" width="300" height="300"></canvas>
+</body>
+<script>
+
+function drawSquares(ctx) {
+ ctx.fillStyle = 'red';
+ ctx.fillRect(0,150,150,150);
+ ctx.fillStyle = 'green';
+ ctx.fillRect(150,150,300,150);
+ ctx.fillStyle = 'blue';
+ ctx.fillRect(0,0,150,150);
+}
+
+async function runTest() {
+ const canvas = document.getElementById('canvas');
+ canvas.width = 300;
+ canvas.height = 300;
+ const ctx = canvas.getContext('2d');
+ drawSquares(ctx);
+}
+
+runTest();
+
+</script>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl-expected.html b/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl-expected.html
new file mode 100644
index 00000000000..4f155316f04
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl-expected.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+
+<body>
+ <p>
+ Test creating an ImageBitmap from the transferToImageBitmap of a webgl OffscreenCanvas, and then
+ transferred to an ImageBitmapRenderingContext.
+ </p>
+ <canvas id="canvas" width="300" height="300"></canvas>
+</body>
+<script>
+
+ function drawSquares(ctx) {
+ ctx.enable(ctx.SCISSOR_TEST);
+ ctx.scissor(0, 150, 150, 150);
+ ctx.clearColor(1, 0, 0, 1);
+ ctx.clear(ctx.COLOR_BUFFER_BIT);
+ ctx.scissor(150, 150, 300, 150);
+ ctx.clearColor(0, 1, 0, 1);
+ ctx.clear(ctx.COLOR_BUFFER_BIT);
+ ctx.scissor(0, 0, 150, 150);
+ ctx.clearColor(0, 0, 1, 1);
+ ctx.clear(ctx.COLOR_BUFFER_BIT);
+ }
+
+ async function runTest() {
+ const canvas = document.getElementById('canvas');
+ canvas.width = 300;
+ canvas.height = 300;
+ const ctx = canvas.getContext('webgl');
+ drawSquares(ctx);
+ }
+
+ runTest();
+
+</script>
diff --git a/Tests/LibWeb/Ref/input/bitmaprenderer-display-list-cache-update.html b/Tests/LibWeb/Ref/input/bitmaprenderer-display-list-cache-update.html
new file mode 100644
index 00000000000..29461ef55af
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/bitmaprenderer-display-list-cache-update.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/canvas-display-list-cache-update-ref.html">
+<canvas id="canvas" height="100" width="100"></canvas>
+<script>
+ async function bitmapOfColor(color) {
+ const source = new OffscreenCanvas(100, 100);
+ const context = source.getContext("2d");
+ context.fillStyle = color;
+ context.fillRect(0, 0, 100, 100);
+ return createImageBitmap(source);
+ }
+
+ (async () => {
+ const context = canvas.getContext("bitmaprenderer");
+ context.transferFromImageBitmap(await bitmapOfColor("rgb(255, 0, 0)"));
+ const green = await bitmapOfColor("rgb(0, 255, 0)");
+
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ context.transferFromImageBitmap(green);
+
+ requestAnimationFrame(() => {
+ if (window.internals)
+ internals.signalTestIsDone("PASS");
+ else
+ document.documentElement.classList.remove("reftest-wait");
+ });
+ });
+ });
+ })();
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped.html b/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped.html
new file mode 100644
index 00000000000..6423df81e0b
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<link rel="match" href="../../../../../../../expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-flipped-expected.html" />
+<body>
+ <p>Test whether the imageOrientation "flipY" works when creating an ImageBitmap from the ImageData of a canvas, and then transfered to an ImageBitmapRenderingContext.</p>
+ <canvas id="canvas" width="300" height="300"></canvas>
+</body>
+<script>
+
+function drawSquares(ctx) {
+ ctx.fillStyle = 'red';
+ ctx.fillRect(0,0,150,150);
+ ctx.fillStyle = 'green';
+ ctx.fillRect(150,0,300,150);
+ ctx.fillStyle = 'blue';
+ ctx.fillRect(0,150,150,300);
+}
+
+async function runTest() {
+ const canvas_temp = document.createElement('canvas');
+ canvas_temp.width = 300;
+ canvas_temp.height = 300;
+ const ctx_temp = canvas_temp.getContext('2d');
+ drawSquares(ctx_temp);
+ const imageSource = ctx_temp.getImageData(0, 0, 300, 300);
+ const imageOrientation = 'flipY';
+ imageIDFlipped = await createImageBitmap(imageSource, 0, 0, 300, 300, { imageOrientation });
+ const canvas = document.getElementById('canvas');
+ const ctx = canvas.getContext('bitmaprenderer');
+ ctx.transferFromImageBitmap(imageIDFlipped);
+}
+
+runTest();
+
+</script>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl.html b/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl.html
new file mode 100644
index 00000000000..e036a9731a7
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<link rel="match" href="../../../../../../../expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-webgl-expected.html" />
+
+<body>
+ <p>
+ Test creating an ImageBitmap from the transferToImageBitmap of a webgl OffscreenCanvas, and then
+ transferred to an ImageBitmapRenderingContext.
+ </p>
+ <canvas id="canvas" width="300" height="300"></canvas>
+</body>
+<script>
+
+ function drawSquares(ctx) {
+ ctx.enable(ctx.SCISSOR_TEST);
+ ctx.scissor(0, 150, 150, 150);
+ ctx.clearColor(1, 0, 0, 1);
+ ctx.clear(ctx.COLOR_BUFFER_BIT);
+ ctx.scissor(150, 150, 300, 150);
+ ctx.clearColor(0, 1, 0, 1);
+ ctx.clear(ctx.COLOR_BUFFER_BIT);
+ ctx.scissor(0, 0, 150, 150);
+ ctx.clearColor(0, 0, 1, 1);
+ ctx.clear(ctx.COLOR_BUFFER_BIT);
+ }
+
+ async function runTest() {
+ const offscreen = new OffscreenCanvas(300, 300);
+ const ctxOffscreen = offscreen.getContext('webgl');
+ drawSquares(ctxOffscreen);
+ const image = offscreen.transferToImageBitmap();
+ const canvas = document.getElementById('canvas');
+ const ctx = canvas.getContext('bitmaprenderer');
+ ctx.transferFromImageBitmap(image);
+ }
+
+ runTest();
+
+</script>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap.html b/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap.html
new file mode 100644
index 00000000000..6aca292c0da
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<link rel="match" href="../../../../../../../expected/wpt-import/html/canvas/element/manual/imagebitmap/imageBitmapRendering-transferFromImageBitmap-expected.html" />
+<body>
+ <p>Test whether the imageOrientation "from-image" works when creating an ImageBitmap from the ImageData of a canvas, and then transfered to an ImageBitmapRenderingContext.</p>
+ <canvas id="canvas" width="300" height="300"></canvas>
+</body>
+<script>
+
+function drawSquares(ctx) {
+ ctx.fillStyle = 'red';
+ ctx.fillRect(0,0,150,150);
+ ctx.fillStyle = 'green';
+ ctx.fillRect(150,0,300,150);
+ ctx.fillStyle = 'blue';
+ ctx.fillRect(0,150,150,300);
+}
+
+async function runTest() {
+ const canvas_temp = document.createElement('canvas');
+ canvas_temp.width = 300;
+ canvas_temp.height = 300;
+ const ctx_temp = canvas_temp.getContext('2d');
+ drawSquares(ctx_temp);
+ const imageSource = ctx_temp.getImageData(0, 0, 300, 300);
+ const imageOrientation = 'from-image';
+ imageIDFlipped = await createImageBitmap(imageSource, 0, 0, 300, 300, { imageOrientation });
+ const canvas = document.getElementById('canvas');
+ const ctx = canvas.getContext('bitmaprenderer');
+ ctx.transferFromImageBitmap(imageIDFlipped);
+}
+
+runTest();
+
+</script>
diff --git a/Tests/LibWeb/Text/expected/all-window-properties.txt b/Tests/LibWeb/Text/expected/all-window-properties.txt
index e7fe64baa5e..6c86ff109ed 100644
--- a/Tests/LibWeb/Text/expected/all-window-properties.txt
+++ b/Tests/LibWeb/Text/expected/all-window-properties.txt
@@ -293,6 +293,7 @@ IIRFilterNode
IdleDeadline
Image
ImageBitmap
+ImageBitmapRenderingContext
ImageData
InputEvent
Int16Array
diff --git a/Tests/LibWeb/Text/expected/canvas/bitmaprenderer.txt b/Tests/LibWeb/Text/expected/canvas/bitmaprenderer.txt
new file mode 100644
index 00000000000..87f5a7532f8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/canvas/bitmaprenderer.txt
@@ -0,0 +1,18 @@
+context: [object ImageBitmapRenderingContext]
+canvas identity: true
+same context again: true
+2d after bitmaprenderer: null
+bitmaprenderer after 2d: null
+bad settings: TypeError
+blank toDataURL matches empty canvas: true
+bitmap detached: 0x0
+canvas attributes after transfer: 4x3
+drawImage of canvas: 0,255,0,255
+createImageBitmap of canvas: 2x5 0,255,0,255
+transfer detached: InvalidStateError
+output kept after failed transfer: 0,255,0,255
+transfer non-bitmap: TypeError
+null transfer: 0,0,0,0
+resized blank toDataURL matches empty canvas: true
+valid output survives resize: 255,0,0,255
+alpha false: [object ImageBitmapRenderingContext]
diff --git a/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.txt b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.txt
new file mode 100644
index 00000000000..9c32466877d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass Test that createImageBitmap from a bitmaprenderer canvas produces correct result
+Pass Test that createImageBitmap on a bitmaprenderer canvas that never consumes any source produces correct result
+Pass Test that createImageBitmap on a bitmaprenderer canvas that consumes null produces correct result
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-creation-with-alpha.txt b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-creation-with-alpha.txt
new file mode 100644
index 00000000000..d18ccbec15a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-creation-with-alpha.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque
+Pass Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha
+Pass Test that the 'alpha' context creation attribute is true by default
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-creation.txt b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-creation.txt
new file mode 100644
index 00000000000..1e71540aca9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-creation.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test that canvas.getContext('bitmaprenderer') returns an instance of ImageBitmapRenderingContext
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-preserves-canvas.txt b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-preserves-canvas.txt
new file mode 100644
index 00000000000..958dcbabd93
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/context-preserves-canvas.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test that ctx.canvas on a ImageBitmapRenderingContext returns the original canvas
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-detached.txt b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-detached.txt
new file mode 100644
index 00000000000..aacac6c846e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-detached.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test transferFromImageBitmap(image) with a detached image should throw InvalidStateError
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-null.txt b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-null.txt
new file mode 100644
index 00000000000..3e24d6dca1c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-null.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test that transferFromImageBitmap(null) discards the previously transferred image
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/canvas/bitmaprenderer.html b/Tests/LibWeb/Text/input/canvas/bitmaprenderer.html
new file mode 100644
index 00000000000..416dcd597c4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/canvas/bitmaprenderer.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ function outcome(f) {
+ try {
+ return `${f()}`;
+ } catch (error) {
+ return error.name;
+ }
+ }
+
+ async function makeBitmap(width, height, color) {
+ const source = document.createElement("canvas");
+ source.width = width;
+ source.height = height;
+ const context = source.getContext("2d");
+ context.fillStyle = color;
+ context.fillRect(0, 0, width, height);
+ return createImageBitmap(source);
+ }
+
+ function pixelsOf(source, width, height) {
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext("2d");
+ context.drawImage(source, 0, 0);
+ return Array.from(context.getImageData(0, 0, width, height).data.slice(0, 4)).join(",");
+ }
+
+ promiseTest(async () => {
+ const canvas = document.createElement("canvas");
+ canvas.width = 4;
+ canvas.height = 3;
+ const context = canvas.getContext("bitmaprenderer");
+ println(`context: ${context}`);
+ println(`canvas identity: ${context.canvas === canvas}`);
+ println(`same context again: ${canvas.getContext("bitmaprenderer") === context}`);
+ println(`2d after bitmaprenderer: ${canvas.getContext("2d")}`);
+ const canvas2d = document.createElement("canvas");
+ canvas2d.getContext("2d");
+ println(`bitmaprenderer after 2d: ${canvas2d.getContext("bitmaprenderer")}`);
+ println(`bad settings: ${outcome(() => document.createElement("canvas").getContext("bitmaprenderer", { get alpha() { throw new TypeError(); } }))}`);
+
+ println(`blank toDataURL matches empty canvas: ${canvas.toDataURL() === (() => { const c = document.createElement("canvas"); c.width = 4; c.height = 3; return c.toDataURL(); })()}`);
+
+ const bitmap = await makeBitmap(2, 5, "rgb(0, 255, 0)");
+ context.transferFromImageBitmap(bitmap);
+ println(`bitmap detached: ${bitmap.width}x${bitmap.height}`);
+ println(`canvas attributes after transfer: ${canvas.width}x${canvas.height}`);
+ println(`drawImage of canvas: ${pixelsOf(canvas, 2, 5)}`);
+ const copy = await createImageBitmap(canvas);
+ println(`createImageBitmap of canvas: ${copy.width}x${copy.height} ${pixelsOf(copy, 2, 5)}`);
+
+ println(`transfer detached: ${outcome(() => context.transferFromImageBitmap(bitmap))}`);
+ println(`output kept after failed transfer: ${pixelsOf(canvas, 2, 5)}`);
+
+ println(`transfer non-bitmap: ${outcome(() => context.transferFromImageBitmap({}))}`);
+
+ context.transferFromImageBitmap(null);
+ println(`null transfer: ${pixelsOf(canvas, 4, 3)}`);
+
+ canvas.width = 7;
+ println(`resized blank toDataURL matches empty canvas: ${canvas.toDataURL() === (() => { const c = document.createElement("canvas"); c.width = 7; c.height = 3; return c.toDataURL(); })()}`);
+
+ const second = await makeBitmap(3, 3, "rgb(255, 0, 0)");
+ context.transferFromImageBitmap(second);
+ canvas.height = 10;
+ println(`valid output survives resize: ${pixelsOf(canvas, 3, 3)}`);
+
+ const opaque = document.createElement("canvas").getContext("bitmaprenderer", { alpha: false });
+ println(`alpha false: ${opaque}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html
new file mode 100644
index 00000000000..ecf854159c8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/bitmaprenderer-as-imagesource.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Canvas's ImageBitmapRenderingContext test</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context">
+<script>
+var width = 10;
+var height = 10;
+
+function testCanvas(ctx, x, y, r, g, b, a)
+{
+ var color = ctx.getImageData(x, y, 1, 1).data;
+ assert_array_equals(color, [r, g, b, a]);
+}
+
+function consumeImageBitmap(image, t)
+{
+ var myCanvas = document.createElement('canvas');
+ myCanvas.width = myCanvas.height = 20;
+ var myCtx = myCanvas.getContext('bitmaprenderer');
+ myCtx.transferFromImageBitmap(image);
+
+ createImageBitmap(myCanvas).then(t.step_func_done(function(imageBitmap) {
+ // Per spec, when transferFromImageBitmap happens, the transferred
+ // ImageBitmap (|image| here) must determine the intrinsic size of
+ // myCanvas, and hence myCanvas.width/height is ignored. Therefore,
+ // |imageBitmap| should have the same size as the |image|.
+ assert_equals(imageBitmap.width, width);
+ assert_equals(imageBitmap.height, height);
+
+ var dstCanvas = document.createElement('canvas');
+ dstCanvas.width = dstCanvas.height = 20;
+ var dstCtx = dstCanvas.getContext('2d');
+ dstCtx.drawImage(myCanvas, 0, 0);
+ testCanvas(dstCtx, 5, 5, 0, 255, 0, 255);
+ testCanvas(dstCtx, 15, 15, 0, 0, 0, 0);
+ }));
+}
+
+async_test(function(t) {
+ var canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#0f0';
+ ctx.fillRect(0, 0, width, height);
+ createImageBitmap(canvas).then(t.step_func(function(image) {
+ consumeImageBitmap(image, t);
+ }));
+}, 'Test that createImageBitmap from a bitmaprenderer canvas produces correct result');
+
+async_test(function(t) {
+ var canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext('bitmaprenderer');
+ createImageBitmap(canvas).then(t.step_func_done(function(image) {
+ assert_equals(image.width, width);
+ assert_equals(image.height, height);
+
+ var dstCanvas = document.createElement('canvas');
+ dstCanvas.width = width;
+ dstCanvas.height = height;
+ var dstCtx = dstCanvas.getContext('2d');
+ dstCtx.drawImage(canvas, 0, 0);
+ testCanvas(dstCtx, 5, 5, 0, 0, 0, 0);
+ }));
+}, 'Test that createImageBitmap on a bitmaprenderer canvas that never consumes any source produces correct result');
+
+
+async_test(function(t) {
+ var canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext('bitmaprenderer');
+ ctx.transferFromImageBitmap(null);
+ createImageBitmap(canvas).then(t.step_func_done(function(image) {
+ assert_equals(image.width, width);
+ assert_equals(image.height, height);
+
+ var dstCanvas = document.createElement('canvas');
+ dstCanvas.width = width;
+ dstCanvas.height = height;
+ var dstCtx = dstCanvas.getContext('2d');
+ dstCtx.drawImage(canvas, 0, 0);
+ testCanvas(dstCtx, 5, 5, 0, 0, 0, 0);
+ }));
+}, 'Test that createImageBitmap on a bitmaprenderer canvas that consumes null produces correct result');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-creation-with-alpha.html b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-creation-with-alpha.html
new file mode 100644
index 00000000000..0eb1f1a1536
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-creation-with-alpha.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Canvas's ImageBitmapRenderingContext test</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context">
+<script>
+var width = 10;
+var height = 10;
+
+function testImageBitmap(image, opts, expectedR, expectedG, expectedB, expectedA)
+{
+ var dstCanvas = document.createElement('canvas');
+ dstCanvas.width = width;
+ dstCanvas.height = height;
+ var dstCtx = dstCanvas.getContext('bitmaprenderer', opts);
+ dstCtx.transferFromImageBitmap(image);
+
+ var myCanvas = document.createElement('canvas');
+ myCanvas.width = width;
+ myCanvas.height = height;
+ var myCtx = myCanvas.getContext('2d');
+ myCtx.drawImage(dstCanvas, 0, 0);
+ var color = myCtx.getImageData(5, 5, 1, 1).data;
+ assert_array_approx_equals(color, [expectedR, expectedG, expectedB, expectedA],1);
+}
+
+promise_test(function() {
+ var srcCanvas = document.createElement('canvas');
+ srcCanvas.width = width;
+ srcCanvas.height = height;
+ var ctx = srcCanvas.getContext('2d');
+ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
+ ctx.fillRect(0, 0, width, height);
+ return createImageBitmap(srcCanvas).then(function(image) {
+ testImageBitmap(image, {alpha: false}, 0, 255, 0, 128);
+ });
+}, "Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque");
+
+promise_test(function() {
+ var srcCanvas = document.createElement('canvas');
+ srcCanvas.width = width;
+ srcCanvas.height = height;
+ var ctx = srcCanvas.getContext('2d');
+ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
+ ctx.fillRect(0, 0, width, height);
+ return createImageBitmap(srcCanvas).then(function(image) {
+ testImageBitmap(image, {alpha: true}, 0, 255, 0, 128);
+ });
+}, "Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha");
+
+promise_test(function() {
+ var srcCanvas = document.createElement('canvas');
+ srcCanvas.width = width;
+ srcCanvas.height = height;
+ var ctx = srcCanvas.getContext('2d');
+ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
+ ctx.fillRect(0, 0, width, height);
+ return createImageBitmap(srcCanvas).then(function(image) {
+ testImageBitmap(image, {}, 0, 255, 0, 128);
+ });
+}, "Test that the 'alpha' context creation attribute is true by default");
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-creation.html b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-creation.html
new file mode 100644
index 00000000000..aea2ff83266
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-creation.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Canvas's ImageBitmapRenderingContext test</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context">
+<script>
+var width = 10;
+var height = 10;
+
+test(function() {
+ var canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext('bitmaprenderer');
+ assert_true(ctx instanceof ImageBitmapRenderingContext);
+}, "Test that canvas.getContext('bitmaprenderer') returns an instance of ImageBitmapRenderingContext");
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-preserves-canvas.html b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-preserves-canvas.html
new file mode 100644
index 00000000000..fa9d3b8fa79
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/context-preserves-canvas.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Canvas's ImageBitmapRenderingContext test</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/canvas.html#the-imagebitmap-rendering-context">
+<script>
+test(function() {
+ var width = 10;
+ var height = 10;
+ var canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext('bitmaprenderer');
+ var dstCanvas = ctx.canvas;
+ assert_true("canvas" in ctx);
+ assert_equals(dstCanvas, ctx.canvas);
+ assert_equals(canvas, ctx.canvas);
+ assert_equals(dstCanvas.width, width);
+ assert_equals(dstCanvas.height, height);
+}, "Test that ctx.canvas on a ImageBitmapRenderingContext returns the original canvas");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-detached.html b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-detached.html
new file mode 100644
index 00000000000..134fbabf5d8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-detached.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Canvas's ImageBitmapRenderingContext test</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context">
+<script>
+var width = 10;
+var height = 10;
+
+promise_test(function() {
+ function testException(image) {
+ var dstCanvas = document.createElement('canvas');
+ dstCanvas.width = width;
+ dstCanvas.height = height;
+ var dstCtx = dstCanvas.getContext('bitmaprenderer');
+ dstCtx.transferFromImageBitmap(image);
+
+ // The image should be detached after transferFromImageBitmap.
+ assert_equals(image.width, 0);
+ assert_equals(image.height, 0);
+ assert_throws_dom("InvalidStateError", function() { dstCtx.transferFromImageBitmap(image); });
+ }
+
+ var srcCanvas = document.createElement('canvas');
+ srcCanvas.width = width;
+ srcCanvas.height = height;
+ var ctx = srcCanvas.getContext('2d');
+ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
+ ctx.fillRect(0, 0, width, height);
+ return createImageBitmap(srcCanvas).then(testException);
+}, "Test transferFromImageBitmap(image) with a detached image should throw InvalidStateError");
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-null.html b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-null.html
new file mode 100644
index 00000000000..f22f722ed9d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/imagebitmap-renderingcontext/transferFromImageBitmap-null.html
@@ -0,0 +1,65 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Canvas's ImageBitmapRenderingContext test</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context">
+<script>
+var width = 10;
+var height = 10;
+
+function testCanvas(bitmapCanvas, r, g, b, a)
+{
+ var myCanvas = document.createElement('canvas');
+ myCanvas.width = width;
+ myCanvas.height = height;
+ var myCtx = myCanvas.getContext('2d');
+ myCtx.drawImage(bitmapCanvas, 0, 0);
+ var color = myCtx.getImageData(5, 5, 1, 1).data;
+ assert_array_equals(color, [r, g, b, a]);
+}
+
+promise_test(function() {
+ function testTransferFromImageBitmapNullability(greenImage, redImage) {
+ var bitmapCanvas = document.createElement('canvas');
+ bitmapCanvas.width = width;
+ bitmapCanvas.height = height;
+ var bitmapCtx = bitmapCanvas.getContext('bitmaprenderer');
+
+ // Make sure the bitmap renderer canvas is filled correctly.
+ bitmapCtx.transferFromImageBitmap(greenImage);
+ testCanvas(bitmapCanvas, 0, 255, 0, 255);
+
+ // Test if passing null resets the bitmap renderer canvas.
+ // Drawing the resetted canvas cannot change the destination canvas.
+ bitmapCtx.transferFromImageBitmap(null);
+ testCanvas(bitmapCanvas, 0, 0, 0, 0);
+
+ // Test if we can redraw the bitmap canvas correctly after reset.
+ bitmapCtx.transferFromImageBitmap(redImage);
+ testCanvas(bitmapCanvas, 255, 0, 0, 255);
+ }
+
+ var greenCanvas = document.createElement('canvas');
+ greenCanvas.width = width;
+ greenCanvas.height = height;
+ var greenCtx = greenCanvas.getContext('2d');
+ greenCtx.fillStyle = '#0f0';
+ greenCtx.fillRect(0, 0, width, height);
+
+ var redCanvas = document.createElement('canvas');
+ redCanvas.width = width;
+ redCanvas.height = height;
+ var redCtx = redCanvas.getContext('2d');
+ redCtx.fillStyle = '#f00';
+ redCtx.fillRect(0, 0, width, height);
+
+ return Promise.all([
+ createImageBitmap(greenCanvas),
+ createImageBitmap(redCanvas),
+ ]).then(([greenImage, redImage]) => {
+ testTransferFromImageBitmapNullability(greenImage, redImage);
+ });
+},'Test that transferFromImageBitmap(null) discards the previously transferred image');
+
+</script>