政府網(wǎng)站作用社群推廣平臺(tái)
文章目錄
- 一、前言
- 1.1、`API`文檔
- 1.2、`Github`倉(cāng)庫(kù)
- 二、圖形
- 2.1、拖拽`draggable`
- 2.2、圖片`Image`
- 2.3、變形`Transformer`
- 三、實(shí)現(xiàn)
- 3.1、依賴
- 3.2、源碼
- 3.2.1、`KonvaContainer`組件
- 3.2.2、`use-key-press`文件
- 3.3、效果圖
- 四、最后
一、前言
本文用到的react-konva
是基于react
封裝的圖形繪制。Konva
是一個(gè)HTML5 Canvas JavaScript
框架,它通過(guò)對(duì) 2d context
的擴(kuò)展實(shí)現(xiàn)了在桌面端和移動(dòng)端的可交互性。Konva
提供了高性能的動(dòng)畫,補(bǔ)間,節(jié)點(diǎn)嵌套,布局,濾鏡,緩存,事件綁定(桌面/移動(dòng)端)等等功能。你可以使用 Konva
在舞臺(tái)上繪制圖形,給圖形添加事件,移動(dòng)、縮放和旋轉(zhuǎn)圖形并且支持高性能的動(dòng)畫即使包含數(shù)千個(gè)圖形。
1.1、API
文檔
英文文檔點(diǎn)擊【前往】,中文文檔點(diǎn)擊【前往】
1.2、Github
倉(cāng)庫(kù)
點(diǎn)擊【前往】訪問(wèn)Github
倉(cāng)庫(kù),在線示例地址,點(diǎn)擊【前往】
二、圖形
在線制圖最基礎(chǔ)的應(yīng)用是拖拽元素,比如,在畫布上拖拽一張圖片或某種形狀,對(duì)該圖片進(jìn)行縮放或旋轉(zhuǎn)操作。
畫布就是<Stage>
,每個(gè)圖層為<Layer>
。
2.1、拖拽draggable
konva
中內(nèi)置了很多形狀的元素,比如圓形、矩形等,以下示例為星型,這里先用<Star>
試一下:
import Konva from 'konva'
import { Circle, Rect, Stage, Layer, Text, Star } from 'react-konva'const Shape = () => {const [star, setStar] = useState({x: 300,y: 300,rotation: 20,isDragging: false,})const handleDragStart = () => {setStar({...star,isDragging: true,})}const handleDragEnd = (e: any) => {setStar({...star,x: e.target.x(),y: e.target.y(),isDragging: false,})}return (<Stage width={1000} height={600}><Layer><Starkey="starid"id="starid"x={star.x}y={star.y}numPoints={5}innerRadius={20}outerRadius={40}fill="#89b717"opacity={0.8}draggablerotation={star.rotation}shadowColor="black"shadowBlur={10}shadowOpacity={0.6}shadowOffsetX={star.isDragging ? 10 : 5}shadowOffsetY={star.isDragging ? 10 : 5}scaleX={star.isDragging ? 1.2 : 1}scaleY={star.isDragging ? 1.2 : 1}onDragStart={handleDragStart}onDragEnd={handleDragEnd}/></Layer></Stage>)
}
其中,可以給 Star
配置一些基礎(chǔ)的屬性,如:x
、y
指該元素在畫布上的坐標(biāo)位置,rotaition
指元素的旋轉(zhuǎn)角度;fill
指元素的填充顏色,scaleX
、scaleY
指元素在 x
、y
軸上的放大比例等等。
在拖拽的時(shí)候,我們要給該元素添加一些拖拽事件,如上:添加 handleDragStart
更改isDragging
屬性,使其在拖動(dòng)時(shí)產(chǎn)生形變;添加 onDragEnd
事件,更改isDragging
和 x
、y
屬性,來(lái)改變拖動(dòng)位置,關(guān)閉拖動(dòng)形變特效等。
觀察上面的代碼發(fā)現(xiàn)某些屬性和react-dnd
類似,但在使用 drag
事件的時(shí)候,發(fā)現(xiàn)比 react-dnd
方便很多,可能因?yàn)榈讓邮?canvas
的原因吧!
2.2、圖片Image
有兩種方式可以導(dǎo)入圖片,一個(gè)是用 react-hooks
,一個(gè)是調(diào)用 react
生命周期函數(shù),這里為了圖省事,用 hooks
。
先安裝 konva
的官方庫(kù)use-image
,use-image
提供好了跨域?qū)傩?code>anonymous,封裝一下圖片組件:
import { Image } from 'react-konva'
import useImage from 'use-image'const KonvaImage = ({ url = '' }) => {const [image] = useImage(url, 'anonymous')return <Image image={image} />
}export default KonvaImage
如果仍顯示跨域問(wèn)題不能生成圖片,需要在服務(wù)器端添加跨域頭或者做一層轉(zhuǎn)發(fā)了。
2.3、變形Transformer
元素變形,需要引用 konva
的Transformer
組件,該組件可以使元素的縮放、旋轉(zhuǎn)。如下代碼,在選中某元素后,會(huì)展示 Transformer
組件,在該組件上存在boundBoxFunc
屬性,當(dāng)用戶觸發(fā)元素的變形行為時(shí),該函數(shù)會(huì)被調(diào)用,返回一個(gè)包含形變后元素的信息(下面代碼中為 newBox
)。
import React, { useState, useEffect, useRef } from 'react'
import { Image, Transformer } from 'react-konva'
import Konva from 'konva'
import useImage from 'use-image'const KonvaImage = ({ url = '', isSelected = false }) => {const [image] = useImage(url)const imgRef = useRef()const trRef = useRef()useEffect(() => {if (isSelected) {trRef.current.nodes([imgRef.current])trRef.current.getLayer().batchDraw()}}, [isSelected])return (<><Image image={image} draggable ref={imgRef} />{isSelected && (<Transformerref={trRef}boundBoxFunc={(oldBox, newBox) => {// limit resizeif (newBox.width < 5 || newBox.height < 5) {return oldBox}const { width, height } = newBox// console.log('width', width);// console.log('height', height);return newBox}}/>)}</>)
}export default KonvaImage
三、實(shí)現(xiàn)
3.1、依賴
安裝如下所需依賴:
npm install react-konva konva use-image --save
3.2、源碼
3.2.1、KonvaContainer
組件
KonvaContainer
圖片框選區(qū)域組件源碼如下所示:
/*** @Description: KonvaContainer圖片框選區(qū)域組件* @props url 需要框選的圖片的URL地址* @props width 寬度* @props height 高度* @props defaultValue 默認(rèn)框選起來(lái)區(qū)域的數(shù)據(jù)* @onChange 回調(diào)方法,通知父組件框選的內(nèi)容信息* @author 小馬甲丫* @date 2023-12-05 03:22:27
*/
import React from 'react';
import useImage from 'use-image';
import { Stage, Layer, Rect, Image, Transformer } from 'react-konva';
import useKeyPress from '@/hooks/use-key-press';/*** 框選的圖片* @param url* @constructor*/
const BackgroundImage = ({ url }) => {const [image] = useImage(url);return <Image image={image} />;
};/*** 背景白板* @param width* @param height* @constructor*/
const BackgroundWhite = ({ width, height }) => {return (<Rectx={0}y={0}width={width}height={height}fill="#fff"id="rectangleBg"name="rectangleBg"/>);
};/*** 框選出來(lái)的框* @param canvas* @param shapeProps* @param onSelect* @param onChange* @constructor*/
const Rectangle = ({ canvas, shapeProps, onSelect, onChange }) => {const shapeRef = React.useRef();return (<RectonClick={() => onSelect(shapeRef)}onTap={() => onSelect(shapeRef)}ref={shapeRef}{...shapeProps}name="rectangle"draggableonMouseOver={() => {document.body.style.cursor = 'move';}}onMouseOut={() => {document.body.style.cursor = 'default';}}onDragEnd={(e) => {onChange({...shapeProps,x: e.target.x(),y: e.target.y(),});}}dragBoundFunc={(pos) => {const shapeWidth = shapeRef.current.attrs.width;const shapeHeight = shapeRef.current.attrs.height;let x = pos.x;if (x <= 0) {x = 0;} else if (x + shapeWidth >= canvas.width) {x = canvas.width - shapeWidth;}let y = pos.y;if (y < 0) {y = 0;} else if (y + shapeHeight > canvas.height) {y = canvas.height - shapeHeight;}return {x,y,};}}onTransformEnd={() => {// transformer is changing scale of the node// and NOT its width or height// but in the store we have only width and height// to match the data better we will reset scale on transform endconst node = shapeRef.current;const scaleX = node.scaleX();const scaleY = node.scaleY();// we will reset it backnode.scaleX(1);node.scaleY(1);onChange({...shapeProps,x: node.x(),y: node.y(),// set minimal valuewidth: Math.max(5, node.width() * scaleX),height: Math.max(node.height() * scaleY),});}}/>);
};/*** 主容器* @param props* @constructor*/
const KonvaContainer = (props) => {const [imageObject, setImageObject] = React.useState({width: props.width,height: props.height,url: props.url,});const [rectanglesField, setRectanglesField] = React.useState([]);const [selectedId, selectShape] = React.useState(null);const trRef = React.useRef();const layerRef = React.useRef();const Konva = window.Konva;const hideTransformer = () => {trRef.current.nodes([]);};/*** 初始化框選框* @param list*/const initRectangles = (list) => {const rects = list.map((item, index) => ({...item,id: `rect_${index}`,fill: 'rgb(160, 76,4, 0.3)',}));setRectanglesField(rects);};/*** 監(jiān)聽prop值變換*/React.useEffect(() => {const {url = '',width = 0,height = 0,defaultValue = [],} = props || {};setImageObject({width,height,url,});hideTransformer();// 圖片地址不一致說(shuō)明變更圖片,需要重置選框if (url !== imageObject.url) {setRectanglesField([]);selectShape(null);}initRectangles(defaultValue);}, [props.url, props.width, props.height, props.defaultValue]);/*** 更新框選框數(shù)據(jù)* @param rects*/const updateRectangles = (rects) => {setRectanglesField(rects);props.onChange(rects);};/*** 添加框選框*/const addRec = () => {const data = rectanglesField;const rects = data.slice();const id = `rect_${rects.length}`;rects[rects.length] = {id,...getSelectionObj(),};updateRectangles(rects);selectShape(id);};/*** 刪除框選框*/const delRec = () => {const data = rectanglesField;const rects = data.slice().filter((rect) => rect.id !== selectedId);updateRectangles(rects);hideTransformer();document.body.style.cursor = 'default';selectShape(null);};const selectionRectRef = React.useRef();const selection = React.useRef({visible: false,x1: 0,y1: 0,x2: 0,y2: 0,});/*** 高亮框選框* @param id*/const activeTransformer = (id) => {const activeRect =layerRef.current.find('.rectangle').find((elementNode) => elementNode.attrs.id === id) ||selectionRectRef.current;trRef.current.nodes([activeRect]);};/*** useKeyPress監(jiān)聽鍵盤按鍵刪除鍵del和返回鍵backspace* 8 返回鍵* 46 刪除鍵*/useKeyPress([8, 46], (e) => {// disable click eventKonva.listenClickTap = false;if (e.target.style[0] === 'cursor') delRec();});/*** 獲取選中的框選框的信息*/const getSelectionObj = () => {return {x: Math.min(selection.current.x1, selection.current.x2),y: Math.min(selection.current.y1, selection.current.y2),width: Math.abs(selection.current.x1 - selection.current.x2),height: Math.abs(selection.current.y1 - selection.current.y2),fill: 'rgb(160, 76,4, 0.3)',};};/*** 更新框選框*/const updateSelectionRect = () => {const node = selectionRectRef.current;node.setAttrs({...getSelectionObj(),visible: selection.current.visible,});node.getLayer().batchDraw();};/*** 開始繪制框選框* @param e*/const onMouseDown = (e) => {const isTransformer = e.target.findAncestor('Transformer');if (isTransformer) {return;}hideTransformer();const pos = e.target.getStage().getPointerPosition();selection.current.visible = true;selection.current.x1 = pos.x;selection.current.y1 = pos.y;selection.current.x2 = pos.x;selection.current.y2 = pos.y;updateSelectionRect();};/*** 繪制框選框中* @param e*/const onMouseMove = (e) => {if (!selection.current.visible) {return;}const pos = e.target.getStage().getPointerPosition();selection.current.x2 = pos.x;selection.current.y2 = pos.y;updateSelectionRect();};/*** 結(jié)束繪制框選框* @param e*/const onMouseUp = (e) => {// 點(diǎn)擊Rect框時(shí),會(huì)返回該Rect的id// 畫框時(shí)鼠標(biāo)在Rect上松開,會(huì)返回該Rect的idconst dragId = e.target.getId();if (!selection.current.visible) {return;}// 是否鼠標(biāo)拖動(dòng),并且偏移量大于10時(shí)才算拖動(dòng)。拖動(dòng)Rect沒(méi)有偏移量,畫框才有偏移量const { current: { x1 = 0, x2 = 0, y1 = 0, y2 = 0 } = {} } = selection || {};const isMove = (x1 !== x2 && Math.abs(x1 - x2) > 10) || (y1 !== y2 && Math.abs(y1 - y2) > 10);// 點(diǎn)擊后有拖動(dòng)就添加Rect框,并且偏移量大于10時(shí)才算拖動(dòng)if (isMove) {addRec();}// 設(shè)置可調(diào)節(jié)大小節(jié)點(diǎn)if (!!dragId && !isMove) {// 點(diǎn)擊已有的Rect框才設(shè)置,并且拖動(dòng)小于10,也就是沒(méi)有拖動(dòng)activeTransformer(dragId);} else if (isMove) {// 拖動(dòng)大于10,生成新的Rect框activeTransformer();}selection.current.visible = false;// disable click eventKonva.listenClickTap = false;updateSelectionRect();};return (<Stagewidth={imageObject.width}height={imageObject.height}onMouseDown={onMouseDown}onMouseUp={onMouseUp}onMouseMove={onMouseMove}><Layer ref={layerRef}><BackgroundWhite {...imageObject} /><BackgroundImage {...imageObject} />{rectanglesField.map((rect, i) => {return (<Rectanglekey={i}getKey={i}canvas={imageObject}shapeProps={rect}isSelected={rect.id === selectedId}getLength={rectanglesField.length}onSelect={() => {selectShape(rect.id);}}onChange={(newAttrs) => {const rects = rectanglesField.slice();rects[i] = newAttrs;updateRectangles(rects);}}/>);})}<Transformerref={trRef}rotationSnaps={[0, 90, 180, 270]}keepRatio={false}anchorSize={4}anchorStroke='#a04c04'anchorFill="#fff"borderStroke='#a04c04'borderDash={[1, 1]}enabledAnchors={['top-left', 'top-right', 'bottom-left', 'bottom-right']}boundBoxFunc={(oldBox, newBox) => {// limit resize// newBox.rotation !== 0進(jìn)入return oldBox,就可實(shí)現(xiàn)不讓旋轉(zhuǎn)if (newBox.width < 20 || newBox.height < 20) {return oldBox;}return newBox;}}/><Rect ref={selectionRectRef} /></Layer></Stage>);
};export default KonvaContainer;
3.2.2、use-key-press
文件
用到了下面這個(gè)hook
文件use-key-press
:
import { useCallback, useEffect, MutableRefObject } from 'react';type keyType = KeyboardEvent['keyCode'] | KeyboardEvent['key'];
type keyFilter = keyType | keyType[];
type EventHandler = (event: KeyboardEvent) => void;
type keyEvent = 'keydown' | 'keyup';
type BasicElement = HTMLElement | Element | Document | Window;
type TargetElement = BasicElement | MutableRefObject<null | undefined>;
type EventOptions = {events?: keyEvent[];target?: TargetElement;
};const modifierKey: any = {ctrl: (event: KeyboardEvent) => event.ctrlKey,shift: (event: KeyboardEvent) => event.shiftKey,alt: (event: KeyboardEvent) => event.altKey,meta: (event: KeyboardEvent) => event.metaKey,
};const defaultEvents: keyEvent[] = ['keydown'];/*** 判斷對(duì)象類型* @param obj 參數(shù)對(duì)象* @returns String*/
function isType<T>(obj: T): string {return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
}/*** 獲取當(dāng)前元素* @param target TargetElement* @param defaultElement 默認(rèn)綁定的元素*/
function getTargetElement(target?: TargetElement, defaultElement?: BasicElement) {if (!target) {return defaultElement;}if ('current' in target) {return target.current;}return target;
}/*** 按鍵是否激活* @param event 鍵盤事件* @param keyFilter 當(dāng)前鍵*/
const keyActivated = (event: KeyboardEvent, keyFilter: any) => {const type = isType(keyFilter);const { keyCode } = event;if (type === 'number') {return keyCode === keyFilter;}const keyCodeArr = keyFilter.split('.');// 符合條件的長(zhǎng)度let genLen = 0;// 組合鍵keyCodeArr.forEach((key) => {const genModifier = modifierKey[key];if ((genModifier && genModifier) || keyCode === key) {genLen++;}});return genLen === keyCodeArr.length;
};/*** 鍵盤按下預(yù)處理方法* @param event 鍵盤事件* @param keyFilter 鍵碼集*/
const genKeyFormate = (event: KeyboardEvent, keyFilter: any) => {const type = isType(keyFilter);if (type === 'string' || type === 'number') {return keyActivated(event, keyFilter);}// 多個(gè)鍵if (type === 'array') {return keyFilter.some((item: keyFilter) => keyActivated(event, item));}return false;
};/*** 監(jiān)聽鍵盤按下/松開* @param keyCode* @param eventHandler* @param options*/
const useKeyPress = (keyCode: keyFilter,eventHandler?: EventHandler,options: EventOptions = {},
) => {const { target, events = defaultEvents } = options;const callbackHandler = useCallback((event) => {if (genKeyFormate(event, keyCode)) {typeof eventHandler === 'function' && eventHandler(event);}},[keyCode],);useEffect(() => {const el = getTargetElement(target, window)!;events.forEach((eventName) => {el.addEventListener(eventName, callbackHandler);});return () => {events.forEach((eventName) => {el.removeEventListener(eventName, callbackHandler);});};}, [keyCode, events, callbackHandler]);
};export default useKeyPress;
3.3、效果圖
頁(yè)面效果如下所示:
四、最后
本人每篇文章都是一字一句碼出來(lái),希望大佬們多提提意見。順手來(lái)個(gè)三連擊,點(diǎn)贊👍收藏💖關(guān)注?。創(chuàng)作不易,給我打打氣,加加油?