import React, { useMemo, Fragment, useRef, useEffect } from 'react'; import { Image as KonvaImage, Transformer } from 'react-konva'; import useImage from 'use-image'; import ProgramConfig from "../../../units"; import { ImageNode } from "./data"; const handleImgUrl = (val: string) => { let src = val; if (src.startsWith("http")) { return src; } if (src.includes("@R@")) { const text = src.split("@R@")[1]; if (text.startsWith("http")) { return text; } src = text; } try { src = JSON.parse(src || "{}").base?.path; } catch { } const url = encodeURI(ProgramConfig.joinPath( ProgramConfig.joinPath(ProgramConfig.api(), "/v3/files"), src )) + `?@token=${ProgramConfig.hydrocarbonToken()}&@programToken=${ProgramConfig.programCode()}&@applicationToken=${ProgramConfig.applicationCode()}`; return url; } interface Props { node: ImageNode; // 当前组件信息 onDragMove?: (e, id: string) => void; isSelected?: boolean; // 是否选中 onSelect?: () => void; // 设置选中 onChange?: (node: ImageNode) => void; // 更新组件配置 isDesignMode?: boolean; // 是否编辑模式 } const Index = (props: Props) => { const { node, onDragMove, isSelected, onSelect, onChange, isDesignMode = true } = props; const { position, size, draggable = true, selected = true, rotation } = node; const nodeRef = useRef(null); const trRef = useRef(null); const imgUrl = useMemo(() => { if (!node?.url) return ""; return handleImgUrl(node.url); }, [node]) const [image] = useImage(imgUrl); // image渲染在画布上需要使用 useEffect(() => { trRef.current.nodes(isDesignMode && selected && isSelected ? [nodeRef.current] : []); // 选中设置可拖拽size }, [isSelected]); // 尺寸拖拽、旋转后执行 const onTransformEnd = () => { const nodeCur = nodeRef.current; const scaleX = nodeCur.scaleX(); const scaleY = nodeCur.scaleY(); const rotation = nodeCur.rotation(); nodeCur.scaleX(1); nodeCur.scaleY(1); onChange({ ...node, position: { x: nodeCur.x(), y: nodeCur.y() }, size: { width: Math.max(5, nodeCur.width() * scaleX), height: Math.max(nodeCur.height() * scaleY) }, rotation }); } return onDragMove?.(e, node.id)} onClick={onSelect} onTransformEnd={onTransformEnd} rotation={rotation || 0} /> { // limit resize if (Math.abs(newBox.width) < 5 || Math.abs(newBox.height) < 5) { return oldBox; } return newBox; }} /> ; }; export default Index;