Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active December 29, 2022 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincentorback/853975959b282268e2a228b1c91dafb0 to your computer and use it in GitHub Desktop.
Save vincentorback/853975959b282268e2a228b1c91dafb0 to your computer and use it in GitHub Desktop.
React native transparent image using canvas
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