我试图使用Konva-React在形状对象中使用fillpatternImage来设置图像,我尝试了一些不同的方法,但显然我需要使用一个Image对象,而不是一个Konva图像来填充PatternImage。
我尝试了几种不同的方法,但显然我需要使用一个Image对象,而不是一个Konva Image来填充PatternImage。
为什么我不能在Konva.Shape.fillPatternImage(imageObj)中使用Konva.Image()?
所以我正在尝试这个....
const GridView = (props) => {
const placeRectImages = props.places.map(({ ...otherProps }, index) => {
const corsProxy = 'https://cors-anywhere.herokuapp.com/' + otherProps.default_image_url
var imageObj = new Image(); /error happens here....
imageObj.src = corsProxy
imageObj.onload = function () {
var canvas = document.createElement("canvas"),
canvasContext = canvas.getContext("2d");
canvasContext.drawImage(imageObj, 0, 0, 30, 30);
var dataURL = canvas.toDataURL();
return <Circle
x={20 * index}
y={20 * index / 2}
width={50}
height={50}
shadowBlur={5}
fillPatternImage={dataURL} // would try passing imageObj if dataURL didn't work
/>
};
但是得到一个错误,说 "TypeError: react_konva__WEBPACK_IMPORTED_MODULE_1__.Image is not a constructor"。
任何关于如何解决这个问题或以其他方式将filpatternimage变成konva形状的想法将被感激......
EDIT. 正如Lavrton下面所说,我从React-Konva导入Image,导致访问全局变量的问题。所以我改变了 Image()
到 window.Image()
仍然没有加载到我的Shape对象中,所以为了让它完全工作,我最后做了这样的工作... ...
const PlaceCircle = (url, index) => {
let timage
const [image, setImage] = useState(null)
useEffect(() => {
loadImage();
}, []);
const loadImage = () => {
timage = new window.Image();
timage.src = url;
timage.addEventListener("load", handleLoad);
}
const handleLoad = () => {
setImage(timage);
}
return (
<Circle
x={20 * index}
y={20 * index / 2}
width={50}
height={50}
shadowBlur={5}
fillPatternImage={image}
/>
);
}
然后使用上面的函数从我的道具中映射...
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
{props.places.map(({ ...otherProps }, index) => {
const corsProxy = otherProps.default_image_url
return PlaceCircle(corsProxy, index)
})}
</Layer>
</Stage>
);
就像你导入的那样 Image
组成部分 react-konva
:
import { Image } from 'react-konva';
这种导入会覆盖全局 Image
对象。
要解决这个问题,你可以
import { Image as KonvaImage } from 'react-konva';
Image
从全局中创建图像。var imageObj = new window.Image();
var imageObj = document.createElement('img');