HTML5 canvas 文本教程
要使用 Konva
创建文本,我们可以实例化一个 Konva.Text()
对象。
有关属性和方法的完整列表,请参见 文本 API 参考。
- Vanilla
- React
- Vue
import Konva from 'konva'; const stage = new Konva.Stage({ container: 'container', width: window.innerWidth, height: window.innerHeight }); const layer = new Konva.Layer(); stage.add(layer); // 简单文本 const simpleText = new Konva.Text({ x: stage.width() / 2, y: 15, text: '简单文本', fontSize: 30, fontFamily: 'Calibri', fill: 'green' }); simpleText.offsetX(simpleText.width() / 2); // 复杂文本与背景 const complexText = new Konva.Text({ x: 20, y: 60, text: "复杂文本\n\n整个世界都是一个舞台,所有的男人和女人只是演员。他们有他们的退场和入场。", fontSize: 18, fontFamily: 'Calibri', fill: '#555', width: 300, padding: 20, align: 'center' }); const rect = new Konva.Rect({ x: 20, y: 60, stroke: '#555', strokeWidth: 5, fill: '#ddd', width: 300, height: complexText.height(), shadowColor: 'black', shadowBlur: 10, shadowOffsetX: 10, shadowOffsetY: 10, shadowOpacity: 0.2, cornerRadius: 10 }); layer.add(rect); layer.add(simpleText); layer.add(complexText);
import { Stage, Layer, Text, Rect } from 'react-konva'; const text = `复杂文本 整个世界都是一个舞台,所有的男人和女人只是演员。他们有他们的退场和入场。`; const App = () => { return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Text x={window.innerWidth / 2} y={15} text="简单文本" fontSize={30} fontFamily="Calibri" fill="green" offsetX={60} // 近似半宽 /> <Rect x={20} y={60} stroke="#555" strokeWidth={5} fill="#ddd" width={300} height={200} // 近似高度 shadowColor="black" shadowBlur={10} shadowOffsetX={10} shadowOffsetY={10} shadowOpacity={0.2} cornerRadius={10} /> <Text x={20} y={60} text={text} fontSize={18} fontFamily="Calibri" fill="#555" width={300} padding={20} align="center" /> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer> <v-rect :config="rectConfig" /> <v-text :config="simpleTextConfig" /> <v-text :config="complexTextConfig" /> </v-layer> </v-stage> </template> <script setup> const stageSize = { width: window.innerWidth, height: window.innerHeight }; const simpleTextConfig = { x: window.innerWidth / 2, y: 15, text: '简单文本', fontSize: 30, fontFamily: 'Calibri', fill: 'green', offsetX: 60 // 近似半宽 }; const complexTextConfig = { x: 20, y: 60, text: "复杂文本\n\n整个世界都是一个舞台,所有的男人和女人只是演员。他们有他们的退场和入场。", fontSize: 18, fontFamily: 'Calibri', fill: '#555', width: 300, padding: 20, align: 'center' }; const rectConfig = { x: 20, y: 60, stroke: '#555', strokeWidth: 5, fill: '#ddd', width: 300, height: 200, // 近似高度 shadowColor: 'black', shadowBlur: 10, shadowOffsetX: 10, shadowOffsetY: 10, shadowOpacity: 0.2, cornerRadius: 10 }; </script>