/ client_code / utils / _canvas_helpers.py
_canvas_helpers.py
 1  # SPDX-License-Identifier: MIT
 2  #
 3  # Copyright (c) 2021 The Anvil Extras project team members listed at
 4  # https://github.com/anvilistas/anvil-extras/graphs/contributors
 5  #
 6  # This software is published at https://github.com/anvilistas/anvil-extras
 7  
 8  from anvil import Canvas as _Canvas
 9  from anvil.js import get_dom_node as _dom_node
10  from anvil.js import window as _window
11  
12  __version__ = "3.1.0"
13  
14  
15  def correct_canvas_resolution(canvas):
16      """call this function in the reset event for a canvas element.
17      It will reduce blurryness of canvas elements on retina screens"""
18      assert isinstance(canvas, _Canvas), "expected a Canvas object as the first argument"
19      dpr = max(_window.devicePixelRatio, 2)
20      dom_c = _dom_node(canvas)
21      rect = dom_c.getBoundingClientRect()
22      new_width = int(rect.width * dpr)
23      if dom_c.width == new_width:
24          # we've done this scaling already
25          return
26      dom_c.width = new_width
27      dom_c.height = int(rect.height * dpr)
28      ctx = dom_c.getContext("2d")
29      # scale all drawing options by the dpr
30      # so we don't worry about the difference
31      ctx.scale(dpr, dpr)