Fix for non-integer devicePixelRatios

This commit is contained in:
Andrew Stephens
2022-12-19 10:10:27 -05:00
parent a1102f3924
commit 1578a9effe

View File

@@ -67,7 +67,7 @@ class ASDitheredImage extends HTMLElement {
if (newValue === "auto") { if (newValue === "auto") {
this.crunchFactor = this.getAutoCrunchFactor() this.crunchFactor = this.getAutoCrunchFactor()
} else if (newValue === "pixel") { } else if (newValue === "pixel") {
this.crunchFactor = 1.0 / window.devicePixelRatio this.crunchFactor = 1.0 / this.getDevicePixelRatio()
} else { } else {
this.crunchFactor = parseInt(newValue, 10) this.crunchFactor = parseInt(newValue, 10)
if (isNaN(this.crunchFactor)) { if (isNaN(this.crunchFactor)) {
@@ -101,12 +101,17 @@ class ASDitheredImage extends HTMLElement {
// If the pixel ratio is 3 or above (like on my iPhone) then even css pixels are too small to make dithering // If the pixel ratio is 3 or above (like on my iPhone) then even css pixels are too small to make dithering
// look effective, so I double the pixels again // look effective, so I double the pixels again
getAutoCrunchFactor() { getAutoCrunchFactor() {
if (window.devicePixelRatio < 3) { if (this.getDevicePixelRatio() < 3) {
return 1 return 1
} else { } else {
return 2 return 2
} }
} }
getDevicePixelRatio() {
// this should always be an integer for the dithering code to work
return Math.floor(window.devicePixelRatio)
}
drawImage() { drawImage() {
if ((this.canvas === undefined) || (this.src === undefined)) { if ((this.canvas === undefined) || (this.src === undefined)) {
@@ -129,9 +134,9 @@ class ASDitheredImage extends HTMLElement {
// canvas backing store to the element size times the devicePixelRatio // canvas backing store to the element size times the devicePixelRatio
// Then, once the image has loaded we draw it manually scaled to only part of the canvas (since the canvas is bigger than the element) // Then, once the image has loaded we draw it manually scaled to only part of the canvas (since the canvas is bigger than the element)
// The dithering algorithm will scale up the image to the canvas size // The dithering algorithm will scale up the image to the canvas size
const logicalPixelSize = window.devicePixelRatio * this.crunchFactor const logicalPixelSize = this.getDevicePixelRatio() * this.crunchFactor
this.canvas.width = rect.width * window.devicePixelRatio this.canvas.width = rect.width * this.getDevicePixelRatio()
this.canvas.height = rect.height * window.devicePixelRatio this.canvas.height = rect.height * this.getDevicePixelRatio()
const image = new Image() const image = new Image()