HTML5 Canvas 混合模式与 globalCompositeOperation 教程
使用 Konva 框架,您可以通过 globalCompositeOperation
属性设置 globalCompositeOperation 或混合模式操作。
说明:拖动红色矩形覆盖绿色文本,以查看异或混合效果。
- 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(); const text = new Konva.Text({ text: '文本阴影!', fontFamily: 'Calibri', fontSize: 40, x: 20, y: 20, fill: 'green', shadowColor: 'white', shadowOffset: { x: 10, y: 10 } }); layer.add(text); const rect = new Konva.Rect({ x: 50, y: 50, width: 100, height: 100, fill: 'red', draggable: true, globalCompositeOperation: 'xor' }); layer.add(rect); stage.add(layer);
import { Stage, Layer, Text, Rect } from 'react-konva'; const App = () => { return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Text text="文本阴影!" fontFamily="Calibri" fontSize={40} x={20} y={20} fill="green" shadowColor="white" shadowOffset={{ x: 10, y: 10 }} /> <Rect x={50} y={50} width={100} height={100} fill="red" draggable={true} globalCompositeOperation="xor" /> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer> <v-text :config="textConfig" /> <v-rect :config="rectConfig" /> </v-layer> </v-stage> </template> <script setup> const stageSize = { width: window.innerWidth, height: window.innerHeight }; const textConfig = { text: '文本阴影!', fontFamily: 'Calibri', fontSize: 40, x: 20, y: 20, fill: 'green', shadowColor: 'white', shadowOffset: { x: 10, y: 10 } }; const rectConfig = { x: 50, y: 50, width: 100, height: 100, fill: 'red', draggable: true, globalCompositeOperation: 'xor' }; </script>