HTML5 Canvas 模糊图像滤镜教程
要对 Konva.Image
应用滤镜,首先需要使用 cache()
函数进行缓存。然后使用 filters()
函数应用滤镜。
要使用 Konva 模糊图像,我们可以使用 Konva.Filters.Blur
滤镜,并通过 blurRadius
属性设置模糊量。
说明:滑动控制条以调整模糊半径。
有关所有可用滤镜,请访问 滤镜文档。
- Vanilla
- React
- Vue
import Konva from 'konva'; const width = window.innerWidth; const height = window.innerHeight; const stage = new Konva.Stage({ container: 'container', width: width, height: height, }); const layer = new Konva.Layer(); stage.add(layer); const imageObj = new Image(); imageObj.onload = () => { const image = new Konva.Image({ x: 50, y: 50, image: imageObj, draggable: true, }); layer.add(image); image.cache(); image.filters([Konva.Filters.Blur]); image.blurRadius(10); const slider = document.createElement('input'); slider.type = 'range'; slider.min = '0'; slider.max = '40'; slider.value = image.blurRadius(); slider.style.position = 'absolute'; slider.style.top = '20px'; slider.style.left = '20px'; slider.addEventListener('input', (e) => { const value = parseInt(e.target.value); image.blurRadius(value); }); document.body.appendChild(slider); }; imageObj.src = 'https://konvajs.org/assets/lion.png'; imageObj.crossOrigin = 'anonymous';
import { Stage, Layer, Image } from 'react-konva'; import { useState, useEffect, useRef } from 'react'; import useImage from 'use-image'; const App = () => { const [blurRadius, setBlurRadius] = useState(10); const [image] = useImage('https://konvajs.org/assets/lion.png', 'anonymous'); const imageRef = useRef(null); useEffect(() => { if (image && imageRef.current) { imageRef.current.cache(); } }, [image]); return ( <> <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Image ref={imageRef} x={50} y={50} image={image} draggable filters={[Konva.Filters.Blur]} blurRadius={blurRadius} /> </Layer> </Stage> <input type="range" min="0" max="40" value={blurRadius} onChange={(e) => setBlurRadius(parseInt(e.target.value))} style={{ position: 'absolute', top: '20px', left: '20px' }} /> </> ); }; export default App;
<template> <div> <v-stage :config="stageSize"> <v-layer> <v-image ref="imageNode" :config="{ x: 50, y: 50, image: image, draggable: true, filters: [Konva.Filters.Blur], blurRadius: blurRadius, }" /> </v-layer> </v-stage> <input type="range" min="0" max="40" :value="blurRadius" @input="handleSlider" style="position: absolute; top: 20px; left: 20px" /> </div> </template> <script setup> import { ref, watch, nextTick } from 'vue'; import { useImage } from 'vue-konva'; import Konva from 'konva'; const stageSize = { width: window.innerWidth, height: window.innerHeight, }; const blurRadius = ref(10); const imageNode = ref(null); const [image] = useImage('https://konvajs.org/assets/lion.png', 'anonymous'); watch(image, async (newImage) => { if (newImage) { await nextTick(); imageNode.value.getNode().cache(); } }); const handleSlider = (e) => { blurRadius.value = parseInt(e.target.value); }; </script>