简体   繁体   中英

React-konva and konva doesn't draw blurred image

Can't make image to be drawn on layer when I apply blur filter. In the parent component I add two instances of my component with konva image. One as is and one with image blur filter. First one draw correctly, the second one show no image. Interestingly if I go to another route and return to this it drawn correctly if I add the same image.

Image is added in componentDidMount:

componentDidMount() {
var img = new Konva.Image({
  image: this.state.imageStateScaled,
  width: 300,
  height: 250
});
let st: Konva.Stage = this.konvaLayer.current.getStage();

if (this.state.blured) {
  img.filters([Konva.Filters.Blur]);
  img.blurRadius(30);
  img.cache({ width: this.konvaLayer.current.getWidth(), height: this.konvaLayer.current.getHeight() });
}

this.konvaLayer.current.add(img);
st.draw();
}

My render function:

 public render() {
let stageWithImage =
  <Stage ref={this.konvaStage} width={300} height={250}>
    <Layer ref={this.konvaLayer}></Layer>
  </Stage>
return ({ stageWithImage })

}

It looks like it caused by konva.image.cache() function. If I put it outside if block and it is applied to both images, non is drawn first time.

Any ideas?

UPDATE I've created a small demo with the issue

source https://github.com/CAIIIA/konvaDrawImageIssue

Live demo http://domit.co.uk/demo/index.html

I've also noticed that all browser works differently with this demo. Chrome as I described above. One image shown, the other only after refresh. Firefox doesn't draw at first hit only after reload Also EDGE browser seems not to have this issue. Works like charm !!!Doesn't work in Internet explorer for some reason at all.

You need to apply filters and cache AFTER image is loaded.

var img = new Konva.Image({
  image: this.props.image,
  width: 300,
  height: 250
});
this.konvaLayer.current.add(img);


this.props.image.onload = () => {
  if (this.props.blurred) {
    img.filters([Konva.Filters.Blur]);
    img.blurRadius(30);
    img.cache({ width: this.konvaLayer.current.getWidth(), height: this.konvaLayer.current.getHeight() });
    this.konvaLayer.current.draw();
  }
}

Offtopic notes:

  1. Try to define all Konva nodes in render function. Do not create them manually with new Konva.Something()
  2. Do not create new Image() in render function. You may have unexpected behavior when you update your components. Take a looks here for demos: https://konvajs.github.io/docs/react/Images.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM