[英]Cannot get image to load into Konva-React, Getting TypeError: react-konva webpack …Image is not a constructor
我正在嘗試使用 Konva-React 在使用 fillpatternImage 的形狀對象中設置圖像。
我嘗試了幾種不同的方法,但顯然我需要使用圖像 object,而不是用於 fillPatternImage 的 Konva 圖像。
為什么我不能在 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()
仍然沒有加載到我的形狀 object 所以為了讓它完全工作,我最終這樣做了..
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}
/>
);
}
然后從我的道具中使用上面的 function 到 map ..
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>
);
就像您從react-konva
導入Image
組件一樣:
import { Image } from 'react-konva';
這樣的導入會覆蓋全局Image
object。
要解決此問題,您可以:
import { Image as KonvaImage } from 'react-konva';
Image
:var imageObj = new window.Image();
var imageObj = document.createElement('img');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.