Last active
December 29, 2022 14:43
-
-
Save vincentorback/853975959b282268e2a228b1c91dafb0 to your computer and use it in GitHub Desktop.
React native transparent image using canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { Animated } from 'react-native' | |
import Canvas, { Image as CanvasImage } from 'react-native-canvas' | |
const TransparentImage = ({ source, width, height, backgroundColor }) => { | |
const fadeAnim = React.useRef(new Animated.Value(0)).current | |
return ( | |
<Animated.View | |
style={{ | |
flex: 1, | |
width: '100%', | |
alignContent: 'center', | |
alignItems: 'center', | |
justifyContent: 'center', | |
opacity: fadeAnim, | |
}} | |
> | |
<Canvas | |
style={{ | |
alignContent: 'center', | |
alignItems: 'center', | |
justifyContent: 'center', | |
flex: 1, | |
width: '100%', | |
}} | |
ref={async (canvas) => { | |
if (!canvas) return null | |
const ctx = canvas.getContext('2d') | |
canvas.width = width | |
canvas.height = height | |
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) | |
ctx.globalCompositeOperation = 'source-over' | |
ctx.fillStyle = backgroundColor | |
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height) | |
const canvasImage = new CanvasImage(canvas) | |
const imageDrawWidth = ctx.canvas.width | |
const imageDrawHeight = ctx.canvas.width | |
canvasImage.addEventListener('error', (err) => { | |
console.log('transparent image error', err) | |
}) | |
canvasImage.addEventListener('load', () => { | |
ctx.globalCompositeOperation = 'multiply' | |
ctx.drawImage( | |
canvasImage, | |
canvas.width / 2 - imageDrawWidth / 2, | |
canvas.height / 2 - imageDrawHeight / 2, | |
imageDrawWidth, | |
imageDrawHeight | |
) | |
Animated.timing(fadeAnim, { | |
useNativeDriver: true, | |
toValue: 1, | |
duration: 100, | |
}).start() | |
}) | |
canvasImage.src = source.uri | |
}} | |
/> | |
</Animated.View> | |
) | |
} | |
export default TransparentImage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment