Search code examples
javascriptkonvajskonva

KonvaJS: Avoid blurriness when zooming in/out


I'm using KonvaJS to draw some figures and make simple animations.

Sometimes a user zooms-in in the page and the drawn canvas gets blurry.

I've noticed that if the page starts zoomed in, the blurriness is greatly reduced. So I thought a solution would be to rerender the stage with the new zoomed value. But I don't know how to do that.

I tried setting Konva.pixelRatio = window.devicePixelRatio then calling stage.draw() (as suggested here: https://stackoverflow.com/a/55524612/3290971), but redrawing isn't enough to remove blurriness. I don't know what would work.

I have this JS Bin that will render a text and a circle. The circle changes color every second, but this is just to see that the interval is working.

At each second, the Konva.pixelRatio is updated, then stage.draw() called. When you zoom in, you'll see both text and circle get blurred and stay blurred at each step.

I also noticed that when calling stage.toDataURL({ pixelRatio: window.devicePixelRatio }), the resulting URL contains a non-blurred image. This is the effect I want to get. I don't know how.

Here's a video of the problem in the JS Bin (the moment the blurriness is gone is when I refresh the page): enter image description here


Solution

  • Already created layers don't update their pixel ratio automatically. So you have to do it by yourself:

    // update global for new layers
    Konva.pixelRatio = window.devicePixelRatio;
    // update pixel ratio of existing canvas
    layer.canvas.setPixelRatio(Konva.pixelRatio);