Images
Images in Mafs are just wrappers around the SVG image
element, with some quality of life improvements tacked on (see below).
import { Coordinates, Image, Mafs, useMovablePoint } from "mafs"
import image from "./mafs.png"
function ImageExample() {
const origin = useMovablePoint([3, 3])
const padding = 0.1
return (
<Mafs viewBox={{ x: [-1, 7], y: [-1, 5] }}>
<Coordinates.Cartesian />
<Image
href={image.src ?? image}
anchor="tl"
x={origin.x + padding}
y={origin.y - padding}/>
<Image
href={image.src ?? image}
anchor="tr"
x={origin.x - padding}
y={origin.y - padding}/>
<Image
href={image.src ?? image}
anchor="bl"
x={origin.x + padding}
y={origin.y + padding}/>
<Image
href={image.src ?? image}
anchor="br"
x={origin.x - padding}
y={origin.y + padding}/>
{origin.element}
</Mafs>
)
}
Props
<Image ... />
View on GitHubName | Description | Default |
---|---|---|
href* | string | β |
x* | number | β |
y* | number | β |
anchor | Indicate where, in the image (top, bottom, left, right, center), the x and y coordinate refers to. Anchor | bl |
width* | number | β |
height* | number | β |
preserveAspectRatio | Whether to preserve the aspect ratio of the image. By default, the image will be centered and scaled to fit the width and height. If you want to squish the image to be the same shape as the box, set this to "none". This is passed directly to the string | β |
svgImageProps | SVGProps<SVGImageElement> | β |
Comparison with SVG <image>
The SVG image
element is a low-level way to include external images in an SVG. It has a few downsides:
- Negative widths and heights lead to undefined behavior.
- The x and y attributes correspond to the top left of the image and is not configurable.
Mafs handles negative heights and widths the way you'd expect; by making the image grow in the -x
and -y
directions.
Additionally, the anchor
attribute of Image
allows you to declare whether the image's x and y coordinates refer to the corners, center of edges, or center of the image.
import { Coordinates, Image, Mafs, useMovablePoint } from "mafs"
import image from "./mafs.png"
function VectorExample() {
const center = useMovablePoint([2, 2])
return (
<Mafs viewBox={{ x: [-1, 7], y: [-1, 5] }}>
<Coordinates.Cartesian />
<Image
href={image.src ?? image}
anchor="tl"
x={center.x + 0.1}
y={center.y - 0.1}/>
<Image
href={image.src ?? image}
anchor="tr"
x={center.x - 0.1}
y={center.y - 0.1}/>
<Image
href={image.src ?? image}
anchor="bl"
x={center.x + 0.1}
y={center.y + 0.1}/>
<Image
href={image.src ?? image}
anchor="br"
x={center.x - 0.1}
y={center.y + 0.1}/>
{center.element}
</Mafs>
)
}