zerodevx / svelte-img

High-performance responsive/progressive images for SvelteKit
https://zerodevx.github.io/svelte-img/
ISC License
300 stars 11 forks source link

Usage in non void elements? #40

Closed LegionDzn closed 4 months ago

LegionDzn commented 4 months ago

Hi, would there be a good way to implement this into non void elements as the background-image style by deconstructing the returned object? I'm a bit new to svelte and JS as a whole, so sorry if this is a dumb question.

leoj3n commented 4 months ago

@LegionDzn For background images you would have to use something like image-set in CSS or object-fit on an HTML <img /> to take advantage of the different sizes and compressed formats, which are not actually generated by svelte-img. The generated images come from vite-imagetools.

You can "deconstruct" the object returned by the import that is passed to the svelte-img <Img /> component...

For instance, this:

import Img from '@zerodevx/svelte-img';
import src from '$lib/assets/1.jpg?w=480;800&as=run';
console.log('src', src);

Logs out that:

src {
  sources: {
    avif: [ [Object], [Object] ],
    webp: [ [Object], [Object] ],
    jpeg: [ [Object], [Object] ]
  },
  img: {
    src: '/@imagetools/2c27dfc12bf9c55bda5dc94183c33a1e6eee810b',
    w: 800,
    h: 600,
    lqip: 'UklGRlYAAABXRUJQVlA4IE...=='
  }
}

You should be able to use the values in that object in CSS, instead of passing it to <Img /> like you normally would:

<Img {src} alt="cat" sizes="(max-width: 600px) 480px, 800px" />
LegionDzn commented 4 months ago

I'll try this, thanks