Ruslan Neck
Ruslan Neck

Reputation: 59

React-konva. Dynamic import SVG

I have a folder with SVG. I need to dynamically add those SVG on Konva's stage. I try to use this component. But it does not work.

const URLImage = (name) => {
  const [image] = useImage(`../images/svg/${name}.svg`);
  return <Image image={image} />;
};

It only works if i do common import:

import mySvg from '../images/svg/mySvg.svg';
....
const [image] = useImage(mySvg);

So what should i do? =)

Upvotes: 2

Views: 1992

Answers (2)

Lojith Vinsuka
Lojith Vinsuka

Reputation: 1049

(Visual representation of @lavrton's answer)

enter image description here

import React, { useState } from 'react'
import { Stage, Layer, Rect, Text, Image } from 'react-konva'
import useImage from 'use-image'

export default function KonvaBoard() {
let initState = {
    isDragging: false,
    x: 50,
    y: 50,
}

const [state, setState] = React.useState(initState)

const convertImage = (imageUrl, index) => {
    const [img] = useImage(imageUrl[0])
    return (
        <Image
            key={index}
            image={img}
            width={100}
            height={100}
            x={imageUrl[1].x}
            y={imageUrl[1].y}
            draggable
        />
    )
}

const logos = [
    ['../assets/icons/angular.svg', { x: 10, y: 10 }],
    ['../assets/icons/css3.svg', { x: 130, y: 30 }],
    ['../assets/icons/flutter.svg', { x: 240, y: 40 }],
]

return (
    <div style={{ textAlign: 'center', minHeight: '90vh' }}>
        <div>KONVA BOARD</div>
        <Stage width={window.innerWidth} height={window.innerHeight}>
            <Layer>
                {logos.map((logo, index) => {
                    return convertImage(logo, index)
                })}
            </Layer>
        </Stage>
    </div>
)
}

Upvotes: 0

lavrton
lavrton

Reputation: 20363

The first code you use will work just fine if you place your images inside a static or public folder. I don't know what bundler you are using, but many of them (parsel, create-react-app, etc) have a special folder for static files.

useImage(url) is not importing a file like in the modules system. In just downloading image from the network address.

As I know import mySvg from '../images/svg/mySvg.svg'; is non-standard, but very popular way of importing static file. Inside mySvg variable you will have an URL to the image that bundler will prepare for you.

Upvotes: 1

Related Questions