Skip to content

Sketch.Text

Sketch.Text 是 Sketch 的文本节点组件,用于在画布上渲染文本内容。
通常作为 Sketch.RootSketch.View 的子节点使用。

示例

React

tsx
import React, { useEffect } from 'react'
import { Sketch, StyleSheet } from '@sketchjs/react'

const styleSheet = StyleSheet.create({
  root: {
    width: 200,
    height: 200,
    backgroundColor: '#fff'
  },
  text: {
    fontSize: 20,
    color: '#000',
    fontWeight: 500
  }
})

export const SketchView: React.FC = () => {
  const sketch = Sketch.useSketch()

  const canvasRef = React.useRef<HTMLCanvasElement>(null)

  const handleSketchElementUpdate = () => 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 (
    <>
      <canvas ref={canvasRef}/>
      <Sketch.Root
        autoRender
        sketch={sketch}
        style={styleSheet.root}
        onUpdate={handleSketchElementUpdate}
        onReady={handleSketchInitialized}
      >
        <Sketch.Text text='hello word!' style={styleSheet.text}/>
      </Sketch.Root>
    </>

  )
}

Vue

tsx
import { defineComponent, onMounted, ref } from 'vue'
import { Sketch, StyleSheet } from '@sketchjs/vue'
import React from 'react'

const styleSheet = StyleSheet.create({
  root: {
    width: 200,
    height: 200,
    backgroundColor: '#fff'
  },
  text: {
    fontSize: 20,
    color: '#000',
    fontWeight: 500
  }
})
export const SketchView = defineComponent({
  name: 'SketchView',
  setup () {
    const sketch = Sketch.useSketch()

    const canvasRef = ref<HTMLCanvasElement | null>(null)

    const handleSketchElementUpdate = () => console.log('sketch update')

    const handleSketchInitialized = () => console.log('sketch initialized')

    const initCanvas = () => {
      const canvas = canvasRef.value
      const ctx = canvas?.getContext('2d')
      if (!canvas || !ctx) return
      return sketch.value.init({ canvas, ctx })
    }

    onMounted(() => initCanvas())

    return () => (
      <>
        <canvas ref="canvasRef"/>
        <Sketch.Root
          autoRender
          sketch={sketch.value}
          style={styleSheet.root}
          onReady={handleSketchInitialized}
          onUpdate={handleSketchElementUpdate}
        >
          <Sketch.Text text='hello word!' style={styleSheet.text}/>
        </Sketch.Root>
      </>
    )
  }
})

API 属性

React

属性说明类型默认值是否必填
text文本内容string-false

Vue

属性说明类型默认值是否必填
text文本内容string-false
style样式StyleSheetDeclaration-false

使用说明 / 注意事项

  • Sketch.Text 必须挂载在 Sketch.RootSketch.View
  • 文本内容通过 text 属性传入
  • 样式建议通过 StyleSheet.create() 管理,包括字体、颜色、对齐方式等
  • 避免在大量文本节点中使用频繁更新,否则可能影响渲染性能

基于 MIT 许可发布