Search code examples
javascriptreactjsphysics-enginematter.js

How to change the texture of a body after the body is created in matter js?


I have added a body called testObj to the world like this

const testObj = Bodies.rectangle(200,200,40,40,)

World.add(engine.current.world, [
  Bodies.rectangle(cw/2, 0, cw, 20, { isStatic: true }),
  Bodies.rectangle(cw/2, ch, cw, 20, { isStatic: true }),
  Bodies.rectangle(0, ch/2 , 20, ch, { isStatic: true }),
  Bodies.rectangle(cw, ch/2 , 20, ch, { isStatic: true }),
  testObj,])

and I have a button like this

<Button onClick={changeTexture}>change</Button>

so when I click this button I want to change the texture of testObj to a image.

( p.s- I am building this website with React if that matters. I'm using useEffect hook to render stuff.)


Solution

  • Update

    OK so I did found a way to do this. Basically I should be able to just do
    testObj2.render.sprite.texture = './Images/Ellipse.png'
    

    and change the texture but I get this error. ( I was able to change the color with render.fillStyle = "red " , but not the sprite texture)

    Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' st
    

    Then I found a GitHub issue about this. This answer solve the problem.

    https://github.com/liabru/matter-js/issues/497#issuecomment-519113260