-
Notifications
You must be signed in to change notification settings - Fork 621
/
Svg.tsx
100 lines (92 loc) 路 2.97 KB
/
Svg.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { Object3DProps, useLoader } from '@react-three/fiber'
import * as React from 'react'
import { forwardRef, Fragment, useMemo } from 'react'
import { Color, DoubleSide, MeshBasicMaterial, Object3D } from 'three'
import { SVGLoader } from 'three-stdlib'
export interface SvgProps extends Object3DProps {
/** src can be a URL or SVG data */
src: string
skipFill?: boolean
skipStrokes?: boolean
strokesWireframe?: boolean
fillWireframe?: boolean
}
export const Svg = forwardRef<Object3D, SvgProps>(function R3FSvg(
{ src, skipFill, skipStrokes, strokesWireframe, fillWireframe, ...props },
ref
) {
const svg = useLoader(SVGLoader, !src.startsWith('<svg') ? src : `data:image/svg+xml;utf8,${src}`)
const shapeGroups = useMemo(
() => (skipFill ? [] : svg.paths.map((path) => SVGLoader.createShapes(path))),
[svg, skipFill]
)
const fillMaterials = useMemo(
() =>
skipFill
? []
: svg.paths.map(
(path) =>
new MeshBasicMaterial({
color: new Color()
.setStyle(path.userData!.style.fill === 'none' ? '#000000' : path.userData!.style.fill)
.convertSRGBToLinear(),
opacity: path.userData!.style.fillOpacity,
transparent: true,
side: DoubleSide,
depthWrite: false,
wireframe: fillWireframe,
})
),
[svg, skipFill, fillWireframe]
)
const strokeMaterials = useMemo(
() =>
skipStrokes
? []
: svg.paths.map(
(path) =>
new MeshBasicMaterial({
color: new Color()
.setStyle(path.userData!.style.stroke === 'none' ? '#000000' : path.userData!.style.stroke)
.convertSRGBToLinear(),
opacity: path.userData!.style.strokeOpacity,
transparent: true,
side: DoubleSide,
depthWrite: false,
wireframe: strokesWireframe,
})
),
[svg, skipStrokes, strokesWireframe]
)
const strokeGeometryGroups = useMemo(
() =>
svg.paths.map((path) =>
skipStrokes
? []
: path.subPaths.map((subPath) => SVGLoader.pointsToStroke(subPath.getPoints(), path.userData!.style))
),
[svg, skipStrokes]
)
return (
<object3D ref={ref} {...props}>
<object3D scale={[1, -1, 1]}>
{strokeGeometryGroups.map((geometries, i) =>
geometries.map((geometry, x) =>
!geometry ? (
<Fragment key={`${i}.${x}`} />
) : (
<mesh key={`${i}.${x}`} geometry={geometry} material={strokeMaterials[i]} />
)
)
)}
{shapeGroups.map((shapes, x) =>
shapes.map((shape, y) => (
<mesh key={`${x}.${y}`} material={fillMaterials[x]}>
<shapeGeometry args={[shape]} />
</mesh>
))
)}
</object3D>
</object3D>
)
})