Skip to content

Truly independent web browser

LibWeb: Draw SVG images without a natural size into a canvas

sideshowbarker98e87acde705
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs
index a1ace4f7af6..7ade5d805ca 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs
@@ -14,9 +14,9 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libcompositing_rust::display_list::canvas_2d_recorder::ColorSpace;
use libcompositing_rust::filter_bytes::FfiFilterFunction;
-use libgfx_rust::Color;
use libgfx_rust::font::FontCascadeListHandle;
use libgfx_rust::image_frame::ImageFrameHandle;
+use libgfx_rust::{Color, IntSize};
use libjs_rust::api::{Gc, Object, Realm};
use super::drawing_state::{CanvasColor, DrawingState};
@@ -82,6 +82,8 @@ unsafe extern "C" {
fn web_canvas_2d_image_source_size(
source_wrapper: *mut c_void,
source_kind: CanvasImageSourceKind,
+ default_width: i32,
+ default_height: i32,
out_width: *mut i32,
out_height: *mut i32,
);
@@ -437,11 +439,19 @@ impl CanvasImageSourceKind {
}
}
- /// The width and the height of the image, as the operations that do not take its size use them.
- pub(crate) fn size(self, source: CppInterface) -> (i32, i32) {
+ /// The width and the height of the image, as the operations that do not take its size use them. An image without a
+ /// natural size is sized against the default object size, the size of the canvas it is drawn into.
+ pub(crate) fn size(self, source: CppInterface, default_object_size: IntSize) -> (i32, i32) {
let (mut width, mut height) = (0, 0);
unsafe {
- web_canvas_2d_image_source_size(source.wrapper().as_ptr().cast(), self, &raw mut width, &raw mut height);
+ web_canvas_2d_image_source_size(
+ source.wrapper().as_ptr().cast(),
+ self,
+ default_object_size.width,
+ default_object_size.height,
+ &raw mut width,
+ &raw mut height,
+ );
}
(width, height)
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
index 429db98991e..b6d1ada4133 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
@@ -207,7 +207,8 @@ pub unsafe extern "C" fn web_canvas_2d_context_draw_image_bitmap(
// SAFETY: The caller passes a live cell of an ImageBitmap.
let image_bitmap = unsafe { cell_from_abi::<ImageBitmap>(image_bitmap) };
let image = CanvasImageSource::ImageBitmap(image_bitmap);
- let (width, height) = image.size();
+ // An ImageBitmap has a size of its own, so no default object size applies to it.
+ let (width, height) = image.size(IntSize::default());
#[allow(
clippy::cast_precision_loss,
reason = "a size of an image becomes a float, as the C++ had it"
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs
index 9e2ccd31a48..281bddc08a0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs
@@ -68,10 +68,11 @@ impl CanvasImageSource {
}
}
- /// The width and the height of the image, as the operations that do not take its size use them.
- pub(crate) fn size(self) -> (i32, i32) {
+ /// The width and the height of the image, as the operations that do not take its size use them. An image without a
+ /// natural size is sized against the default object size, the size of the canvas it is drawn into.
+ pub(crate) fn size(self, default_object_size: IntSize) -> (i32, i32) {
match self.cpp_source() {
- Some((source, kind)) => kind.size(source),
+ Some((source, kind)) => kind.size(source, default_object_size),
None => {
let Self::ImageBitmap(image_bitmap) = self else {
unreachable!("an image source that is not implemented in C++ is an ImageBitmap");
@@ -127,11 +128,18 @@ impl CanvasImageSource {
return self.frame().map(|frame| (frame, source_rect));
};
let kind = self.cpp_source().expect("an image element is implemented in C++").1;
- let (natural_width, natural_height) = kind.size(source);
+ let (natural_width, natural_height) = kind.size(source, canvas_size);
+ if natural_width <= 0 || natural_height <= 0 {
+ return kind.frame(source).map(|frame| (frame, source_rect));
+ }
let scale_x = destination_rect.width / source_rect.width * transform.x_scale();
let scale_y = destination_rect.height / source_rect.height * transform.y_scale();
- if natural_width <= 0 || natural_height <= 0 || (scale_x <= 1.0 && scale_y <= 1.0) {
- return kind.frame(source).map(|frame| (frame, source_rect));
+ if scale_x <= 1.0 && scale_y <= 1.0 {
+ // A vector image without a natural size has no frame of its own, so it's rasterized at the size it's drawn
+ // from.
+ return kind
+ .frame_rasterized_at(source, natural_width, natural_height)
+ .map(|(frame, _)| (frame, source_rect));
}
// The image is rasterized at one scale in both directions, as the vector image would be fitted into a raster of
@@ -353,7 +361,7 @@ impl<K: CanvasKind> RenderingContext2D<K> {
// If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's natural
// width in image pixels, and the image's natural height in image pixels, respectively.
let (dx, dy) = (float(dx), float(dy));
- let (width, height) = image.size();
+ let (width, height) = image.size(self.size());
let (width, height) = (int_to_float(width), int_to_float(height));
self.draw_image_internal(image, 0.0, 0.0, width, height, dx, dy, width, height)
}
@@ -372,7 +380,7 @@ impl<K: CanvasKind> RenderingContext2D<K> {
// If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's natural
// width in image pixels, and the image's natural height in image pixels, respectively.
let (dx, dy, dw, dh) = (float(dx), float(dy), float(dw), float(dh));
- let (width, height) = image.size();
+ let (width, height) = image.size(self.size());
let (width, height) = (int_to_float(width), int_to_float(height));
self.draw_image_internal(image, 0.0, 0.0, width, height, dx, dy, dw, dh)
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
index c0af67c74ce..b65e8de77d9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
@@ -44,7 +44,8 @@ pub(crate) fn read_back_current_video_frame(video: CppInterface, color_space: Co
let transport = video_transport(video)?;
let mut recorder = Recorder::new(transport);
- let (width, height) = CanvasImageSourceKind::HTMLVideoElement.size(video);
+ // A video has a size of its own, so no default object size applies to it.
+ let (width, height) = CanvasImageSourceKind::HTMLVideoElement.size(video, IntSize::default());
let frame_rect = IntRect {
x: 0,
y: 0,
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index df6ca5da987..aa4c1d684b0 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -26,6 +26,7 @@
#include <LibWeb/CSS/FontResolution.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyID.h>
+#include <LibWeb/CSS/Sizing.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleValues/FilterStyleValue.h>
#include <LibWeb/CSS/StyleValues/FontStyleStyleValue.h>
@@ -174,7 +175,7 @@ void web_canvas_2d_style_value_ref(CSS::StyleValue const*);
void web_canvas_2d_style_value_unref(CSS::StyleValue const*);
Gfx::DecodedImageFrame* web_canvas_2d_image_frame_from_pixels(u8 const* first_row, size_t pitch, i32 width, i32 height, u8 color_space);
u8 web_canvas_2d_check_usability_of_image(void* source_wrapper, CanvasImageSourceKind, FlatPtr* out_message);
-void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind, i32* out_width, i32* out_height);
+void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind, i32 default_width, i32 default_height, i32* out_width, i32* out_height);
bool web_canvas_2d_image_is_not_origin_clean(void* source_wrapper, CanvasImageSourceKind);
bool web_canvas_2d_image_source_canvas_id(void* source_wrapper, CanvasImageSourceKind, u64* out_canvas_id, bool* out_source_is_2d);
Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, CanvasImageSourceKind, i32 raster_width, i32 raster_height, bool* out_rasterized);
@@ -749,33 +750,18 @@ u8 web_canvas_2d_check_usability_of_image(void* source_wrapper, CanvasImageSourc
return usability.value() == CanvasImageSourceUsability::Good ? usability_good : usability_bad;
}
-void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind kind, i32* out_width, i32* out_height)
+// The size of an image element's image, as drawing it uses it. The default object size is the size of the output bitmap
+// of the canvas it's drawn into.
+void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind kind, i32 default_width, i32 default_height, i32* out_width, i32* out_height)
{
- auto image_provider_intrinsic_size = [](Layout::ImageProvider const& image_provider) -> Optional<Gfx::IntSize> {
- auto intrinsic_width = image_provider.intrinsic_width();
- auto intrinsic_height = image_provider.intrinsic_height();
- if (!intrinsic_width.has_value() || !intrinsic_height.has_value())
- return {};
- return Gfx::IntSize { intrinsic_width->to_int(), intrinsic_height->to_int() };
- };
-
- auto size = image_source_from(source_wrapper, kind).visit([&](GC::Ref<HTMLImageElement> source) -> Gfx::IntSize {
- if (auto intrinsic_size = image_provider_intrinsic_size(*source); intrinsic_size.has_value())
- return *intrinsic_size;
-
- // FIXME: This is very janky and not correct.
- return { source->width(), source->height() }; }, [&](GC::Ref<SVG::SVGImageElement> source) -> Gfx::IntSize {
- if (auto intrinsic_size = image_provider_intrinsic_size(*source); intrinsic_size.has_value())
- return *intrinsic_size;
-
- // FIXME: This is very janky and not correct.
- auto maybe_width = source->width()->anim_val()->value();
- auto maybe_height = source->height()->anim_val()->value();
-
- 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 {
+ auto size = image_source_from(source_wrapper, kind).visit([&](OneOf<GC::Ref<HTMLImageElement>, GC::Ref<SVG::SVGImageElement>> auto const& source) -> Gfx::IntSize {
+ // https://html.spec.whatwg.org/multipage/canvas.html#drawing-images
+ // If the image has no natural dimensions, then the concrete object size must be used instead, as determined
+ // using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having neither a definite
+ // width nor height, nor any additional constraints, the object's natural properties being those of the image
+ // argument, and the default object size being the size of the output bitmap.
+ auto size = CSS::run_default_sizing_algorithm({}, {}, { source->intrinsic_width(), source->intrinsic_height(), source->intrinsic_aspect_ratio() }, { default_width, default_height });
+ return { size.width().to_int(), size.height().to_int() }; }, [](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();
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
index c6ab08c97ce..b61d2d73a58 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
@@ -20,10 +20,11 @@ static bool image_provider_is_usable_for_canvas(Layout::ImageProvider const& ima
if (!image_provider.is_image_available())
return false;
+ // An image without a natural width or height, such as an SVG image without an absolute width and height, is usable:
+ // Drawing it uses its concrete object size instead. Only a natural dimension of zero makes it unusable.
auto intrinsic_width = image_provider.intrinsic_width();
auto intrinsic_height = image_provider.intrinsic_height();
- return intrinsic_width.has_value() && intrinsic_height.has_value()
- && *intrinsic_width > 0 && *intrinsic_height > 0;
+ return (!intrinsic_width.has_value() || *intrinsic_width > 0) && (!intrinsic_height.has_value() || *intrinsic_height > 0);
}
// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
diff --git a/Tests/LibWeb/Text/expected/canvas/drawImage-svg-without-natural-size.txt b/Tests/LibWeb/Text/expected/canvas/drawImage-svg-without-natural-size.txt
new file mode 100644
index 00000000000..f061e2ab9ab
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/canvas/drawImage-svg-without-natural-size.txt
@@ -0,0 +1,12 @@
+viewBox="0 0 20 20"
+ drawn at its own size: (5,5) 0,255,0,255, (30,30) 0,255,0,255
+ drawn at 20x20: (5,5) 0,255,0,255, (30,30) 0,0,0,0
+width="20"
+ drawn at its own size: (5,5) 0,255,0,255, (30,30) 0,0,0,0
+ drawn at 20x20: (5,5) 0,255,0,255, (30,30) 0,0,0,0
+viewBox="0 0 20 20" width="100%" height="100%"
+ drawn at its own size: (5,5) 0,255,0,255, (30,30) 0,255,0,255
+ drawn at 20x20: (5,5) 0,255,0,255, (30,30) 0,0,0,0
+width="20" height="20"
+ drawn at its own size: (5,5) 0,255,0,255, (30,30) 0,0,0,0
+ drawn at 20x20: (5,5) 0,255,0,255, (30,30) 0,0,0,0
diff --git a/Tests/LibWeb/Text/input/canvas/drawImage-svg-without-natural-size.html b/Tests/LibWeb/Text/input/canvas/drawImage-svg-without-natural-size.html
new file mode 100644
index 00000000000..720c536aa2c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/canvas/drawImage-svg-without-natural-size.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ function svgImage(attributes) {
+ const image = new Image();
+ image.src = "data:image/svg+xml," + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" ${attributes}><rect width="20" height="20" fill="lime"/></svg>`);
+ return image;
+ }
+
+ // The image is drawn into a 40x40 canvas, which is the default object size for an image without a natural size.
+ function pixelsAfterDrawing(image, ...size) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 40;
+ canvas.height = 40;
+ const context = canvas.getContext("2d");
+ context.drawImage(image, 0, 0, ...size);
+ const pixel = (x, y) => Array.from(context.getImageData(x, y, 1, 1).data).join(",");
+ return `(5,5) ${pixel(5, 5)}, (30,30) ${pixel(30, 30)}`;
+ }
+
+ asyncTest(async done => {
+ for (const attributes of ['viewBox="0 0 20 20"', 'width="20"', 'viewBox="0 0 20 20" width="100%" height="100%"', 'width="20" height="20"']) {
+ const image = svgImage(attributes);
+ await image.decode();
+ println(`${attributes}`);
+ println(` drawn at its own size: ${pixelsAfterDrawing(image)}`);
+ println(` drawn at 20x20: ${pixelsAfterDrawing(image, 20, 20)}`);
+ }
+ done();
+ });
+</script>