Skip to content

use window.devicePixelRatio for hidpi displays #209

Description

@mayfield

If the canvas element is scaled by window.devicePixelRatio and then scaled back down by the CSS properties the results look better on HiDPI displays. Given the small nature of most sparklines, this is pretty huge. #nopun

Here are two images from my use case. First with stock code...
image

And here with a modified _calculatePixelDims...
image

Those results come from this incomplete patch:

index 721e03b..805aa12 100644
--- a/src/site/jquery.sparkline.js
+++ b/src/site/jquery.sparkline.js
@@ -2626,19 +2626,13 @@
          */
         _calculatePixelDims: function (width, height, canvas) {
             // XXX This should probably be a configurable option
-            var match;
-            match = this._pxregex.exec(height);
-            if (match) {
-                this.pixelHeight = match[1];
-            } else {
-                this.pixelHeight = $(canvas).height();
-            }
-            match = this._pxregex.exec(width);
-            if (match) {
-                this.pixelWidth = match[1];
-            } else {
-                this.pixelWidth = $(canvas).width();
-            }
+            const heightMatch = this._pxregex.exec(height);
+            const pixelHeight = heightMatch ?  Number(heightMatch[1]) : $(canvas).height();
+            const widthMatch = this._pxregex.exec(width);
+            const pixelWidth = widthMatch ?  Number(widthMatch[1]) : $(canvas).width();
+            const dpr = window.devicePixelRatio || 1;
+            this.pixelHeight = Math.round(pixelHeight * dpr);
+            this.pixelWidth = Math.round(pixelWidth * dpr);
         },
 
         /**
@@ -2710,7 +2704,7 @@
             this.shapes = {};
             this.shapeseq = [];
             this.currentTargetShapeId = undefined;
-            $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
+            $(this.canvas).css({width, height});
         },
 
         _getContext: function (lineColor, fillColor, lineWidth) {

I'd be happy to complete the work on this (hover over is broken) and write it using more compatible code (e.g. no const) if this project is still active (last commit 2013). Otherwise I'll probably fork and put my changes up there.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions