我正在尝试使用 Konva-React 在使用 fillpatternImage 的形状对象中设置图像。
我尝试了几种不同的方法,但显然我需要使用 Image 对象,而不是用于 fillPatternImage 的 Konva Image。
为什么我不能在 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 不是构造函数”
任何关于如何将这个或其他填充模式图像解决为 konva 形状的想法将不胜感激......
编辑。正如下面 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>
);