快速开始(React)
前置准备
- React 16.8+(需要 Hooks)
- 支持 Canvas 的浏览器环境
适用场景
- React 项目中的 Canvas UI
- 需要组件化组织复杂绘图
安装
sh
$ npm add @sketchjs/reactsh
$ pnpm add @sketchjs/reactsh
$ yarn add @sketchjs/reactsh
$ bun add @sketchjs/react基础用法
tsx
import React, { useEffect, useRef } from 'react'
import { Sketch } from '@sketchjs/react'
import { styleSheet } from './styleSheet'
import logo from './logo.png'
function App () {
const sketch = Sketch.useSketch()
const canvasRef = useRef<HTMLCanvasElement>(null)
const handleToDataURL = () => {
const dataUrl = sketch.toDataURL('image/png', 1)
console.log({ dataUrl })
}
const handleSketchUpdate = () => {
console.log('sketch update')
}
const handleSketchInitialized = () => {
console.log('sketch initialized')
}
const initSketch = () => {
const canvas = canvasRef.current
const ctx = canvas?.getContext('2d')
if (!canvas || !ctx) return
return sketch.init({ canvas, ctx })
}
useEffect(() => {
initSketch()
}, [])
return (
<div className="App" onClick={handleToDataURL}>
<canvas className="sketch-canvas" ref={canvasRef}/>
<Sketch.Root
autoRender
sketch={sketch}
style={styleSheet.root}
onReady={handleSketchInitialized}
onUpdate={handleSketchUpdate}>
<Sketch.View style={styleSheet.view}>
<Sketch.Image src={logo} style={styleSheet.logo}/>
<Sketch.Text text="Hello World!" style={styleSheet.text}/>
</Sketch.View>
</Sketch.Root>
</div>
)
}
export default Appts
import { StyleSheet } from '@sketchjs/react'
export const styleSheet = StyleSheet.create({
root: {
width: 500,
height: 500,
backgroundColor: '#282c34'
},
view: {
width: 500,
height: 500,
justifyContent: 'center',
alignItems: 'center'
},
logo: {
width: 200,
height: 200
},
text: {
width: 500,
marginTop: 20,
color: '#ffffff',
fontSize: 50,
fontWeight: 400,
lineHeight: 50,
textAlign: 'center'
}
})使用说明
Sketch.Root需要传入sketch实例,并在init完成后开始渲染- 设置
autoRender后,初始化与更新会自动触发render - Canvas 的像素尺寸由
Sketch.Root的样式决定,建议明确width/height - 若需要手动控制渲染时机,设置
autoRender={false}并调用sketch.render()
配置提示
- 若需要异步加载或跨端能力,请结合 Taro 与对应插件配置
初始化流程
Sketch.useSketch()创建实例- 获取
canvas与ctx - 调用
sketch.init({ canvas, ctx }) - 在
Sketch.Root中挂载节点树并渲染
常见问题
- 为什么画布是空白的?
- 请确认
canvas和ctx都有效,并且Sketch.Root设置了width/height - 组件更新后没有重新渲染?
- 开启
autoRender或在更新后手动调用sketch.render()