iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💡
Minimal code to generate images from canvas in React
In this article, I will introduce how to generate images from a canvas using React (and TypeScript).
I will explain it using examples such as drawing text and changing colors.
Base Code for Using Canvas in React
import React, { useEffect, useState } from 'react'
const width = 255
const height = 255
function App() {
const [png, setPng] = useState<string | null>(null)
useEffect(() => {
const canvasElem = document.createElement('canvas')
canvasElem.width = width
canvasElem.height = height
const ctx = canvasElem.getContext('2d')
// draw
ctx.clearRect(0, 0, width, height)
ctx.fillStyle = '#888888'
ctx.fillRect(0, 0, width, height)
setPng(canvasElem.toDataURL())
}, [])
return (
<div>
<h3>画像生成</h3>
<h4>生成</h4>
{png && (
<div className="comp" style={{ display: 'flex' }}>
<img alt="icon" src={png} />
<img alt="round icon" src={png} style={{ borderRadius: '100%' }} />
</div>
)}
</div>
)
}
export default App
Inside useEffect, we are doing the following:
- Preparing the
HTMLCanvasElementand context - Drawing with the context
- Creating a dataURL with
HTMLCanvasElement#toDataURL()
Rendering with an img tag makes it easier to style.
On mobile browsers, it may not be possible to download images directly from a canvas tag, so this approach makes it easier to support exporting.
Example of Changing Text and Background Colors
oembed: https://codesandbox.io/embed/canvas-img-f7bw7?fontsize=14&hidenavigation=1&theme=dark
Create state variables for drawing using useState and add them to the deps of useEffect.
const [bgColor, setBgColor] = useState<string>('#888888')
const [foColor, setFoColor] = useState<string>('#000000')`
useEffect(() => {
const canvasElem = document.createElement('canvas')
canvasElem.width = width
canvasElem.height = height
const ctx = canvasElem && canvasElem.getContext('2d')
if (!canvasElem || !ctx) return
// draw
ctx.clearRect(0, 0, width, height)
ctx.fillStyle = bgColor
ctx.fillRect(0, 0, width, height)
ctx.font = '30px Hiragino Maru Gothic Pro'
ctx.fillStyle = foColor
ctx.fillText('Hello ハロー', width / 6, height / 2)
setPng(canvasElem.toDataURL())
}, [bgColor, foColor])
The part that calls setState on the form side is as follows:
<>
<h4>背景色</h4>
{['#f00', '#0f0', '#00f'].map((color) => (
<button
key={color}
style={{ background: color }}
onClick={() => setBgColor(color)}
>
{color}
</button>
))}
<h4>文字色</h4>
{['#f00', '#0f0', '#00f'].map((color) => (
<button style={{ color }} onClick={() => setFoColor(color)}>
{color}
</button>
))}
</>
Discussion