我是一个比较新的反应,我会陷入困境时,试图整合
KonvaJS
让他做出反应。我试着按照
Konva Overview
:
// first we need to create a stage
var stage = new Konva.Stage({
container: 'container', // id of container <div>
width: 500,
height: 500
});
// then create layer
var layer = new Konva.Layer();
// create our shape
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
// add the shape to the layer
layer.add(circle);
// add the layer to the stage
stage.add(layer);
// draw the image
layer.draw();
所以我创建了自己的文件
KonvaDrawer.js
import Konva from 'konva';
function KonvaDrawer() {
// first we need to create a stage
var stage = new Konva.Stage({
container: 'container', // id of container <div>
width: 500,
height: 500
});
// then create layer
var layer = new Konva.Layer();
// create our shape
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
// add the shape to the layer
layer.add(circle);
// add the layer to the stage
stage.add(layer);
// draw the image
layer.draw();
}
export default KonvaDrawer;
然后在我的应用程序.js我创造了
div
带着一个
id="container"
正如上面提到的代码,它需要有一个具有该id的div(或者这就是我所理解的)
import React from 'react';
import './App.css';
function App() {
return (
<div id="container"></div>
);
}
export default App;
最后是索引.js我称之为
KonvaDrawer
功能:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import KonvaDrawer from './KonvaDrawer';
ReactDOM.render(
<React.StrictMode>
<App />
{KonvaDrawer()}
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
serviceWorker.unregister();
但是当我这么做的时候
npm start
我得到这个错误:
Stage.js:105 Uncaught Can not find container in document with id container
所以,我不知道为什么会这样,
我在网上找到的所有示例都创建了如下Konva组件:
<Stage>
<Layers>
<Shapes>
例如
here
和
here
但我很好奇我尝试的方法是否可行,以及为什么它目前不起作用。
所以,如果我按照上面的结构来做:
import React from 'react';
import './App.css';
import {Stage, Layer, Circle} from 'react-konva';
function App() {
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Circle x={window.innerWidth / 2}
y={window.innerHeight / 2}
radius={70}
fill={'red'}
stroke={'black'}
strokeWidth={4}
/>
</Layer>
</Stage>
);
}
export default App;
它正确地显示了一个红色圆圈,但是如果我想用for循环自动创建某个对象的层,或者用Javascript创建元素,那么我该怎么做呢?