0

im trying to implement a scratch card in Reactjs, when the component mount I'm able to load an image on the canvas to scratch it, the issue is when I click to reload the scratch card to play again I'm not able to reload an image, only a background color. is there a way to reload the image

componentDidMount() {
    const canvas = this.canvas;
    canvas.width = canvas.parentElement.offsetWidth;
    canvas.height = canvas.parentElement.offsetHeight;

    canvas.addEventListener("mousedown", this.touchStart);
    canvas.addEventListener("touchstart", this.touchStart);
    canvas.addEventListener("mousemove", this.touchMove);
    canvas.addEventListener("touchmove", this.touchMove);
    canvas.addEventListener("mouseup", this.touchEnd);
    canvas.addEventListener("touchend", this.touchEnd);

    this.ctx = canvas.getContext("2d");

    this.brush = new Image();
    this.brush.src = require("../../../assets/images/brush.png");

    this.cover = new Image();
    this.cover.src = require("../../../assets/images/ae-unscratched.png");
    this.cover.onload = () =>
        this.ctx.drawImage(this.cover, 0, 0, canvas.width, canvas.height);
}
reloadCard() {
    this.ctx = this.canvas.getContext("2d");
    this.ctx.globalCompositeOperation = "destination-over";
    this.ctx.fillStyle = "#ffecc0";
    let width = 310;
    let height = 350;

    this.ctx.fillRect(0, 0, width, height);
    this.ctx.save();
}

I tried to initialize a new image like on componentdidmount it didn't work, any idea how can I reload the image?

1 Answers1

0

You could try and add a cache killer query string attribute to your src value:

this.cover.src = require(`../../../assets/images/ae-unscratched.png?${Date.now()}`);
Espen
  • 2,456
  • 1
  • 16
  • 25