我对 React 比较陌生,在尝试将KonvaJS集成到 React 时遇到了困难。我正在尝试遵循Konva 概述中显示的第一个示例:
// 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;
然后在我的 App.js 中,我使用上面的代码创建了div它id="container"需要有一个具有该 id 的 div(或者这就是我所理解的)
import React from 'react';
import './App.css';
function App() {
return (
<div id="container"></div>
);
}
export default App;
最后是我调用KonvaDrawer函数的 index.js:
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')
);
手掌心
相关分类