【发布时间】:2022-03-24 08:36:18
【问题描述】:
我用 matter.js 构建了一个 react 网站。我正在使用useEffect 钩子将内容渲染到带有matter.js 的画布上(我发现大部分代码here)。但是,当我尝试在画布上绘制任何其他内容时,什么也没有出现。一切与重要.js 相关的工作。
const scene = useRef()
const isDragging = useRef(false)
const engine = useRef(Engine.create())
useEffect(() => {
const cw = 1100;
const ch = 700;
const render = Render.create({
canvas: scene.current,
engine: engine.current,
options: {
width: cw,
height: ch,
wireframes: false,
background: 'transparent'
}
})
console.log("gravity " + engine.current.gravity.y + "x : " + engine.current.gravity.x)
let mouse = Mouse.create(render.canvas);
let mouseConstraint = MouseConstraint.create(engine.current, {
mouse: mouse,
constraint: {
render: {
visible: false
}
}
})
render.mouse = mouse;
World.add(engine.current.world, [
Bodies.rectangle(cw / 2, 0, cw, 20, {
isStatic: true,
density: 1
}),
Bodies.rectangle(cw / 2, ch, cw, 20, {
isStatic: true,
density: 1
}),
Bodies.rectangle(0, ch / 2, 20, ch, {
isStatic: true,
density: 1
}),
Bodies.rectangle(cw, ch / 2, 20, ch, {
isStatic: true,
density: 1
}),
mouseConstraint,
])
Runner.run(engine.current)
Render.run(render)
Events.on(mouseConstraint, "mousedown", function(event) {
handleSelections(mouseConstraint.body)
})
Events.on(mouseConstraint, "startdrag", function(event) {
isDragging.current = true
})
Events.on(mouseConstraint, "enddrag", function() {
isDragging.current = false
})
Events.on(engine.current, 'afterUpdate', function() {
countTen.current = countTen.current + 1;
if (countTen.current == 10) {
countTen.current = 0;
if (selectedObjectRef.current != null) {
setGraphingPos(selectedObjectRef.current.velocity.y * -1);
setTicks(ticks + 1)
}
}
})
// ******************* This part doesn't work **************************
scene.current.getContext('2d').beginPath();
scene.current.getContext('2d').arc(100, 100, 20, 0, 2 * Math.PI, false);
scene.current.getContext('2d').fillStyle = 'red';
scene.current.getContext('2d').fill();
// **********************************************************************
return () => {
Render.stop(render)
World.clear(engine.current.world)
Engine.clear(engine.current)
render.canvas.remove()
render.canvas = null
render.context = null
render.textures = {}
}
}, [])
<canvas ref={scene} onClick={ handleMouseDown} className='main-canvas'></canvas>
非常感谢任何形式的帮助!
【问题讨论】:
标签: javascript html reactjs react-hooks matter.js