Skip to content

Instantly share code, notes, and snippets.

@alex-fomin
Last active December 9, 2021 07:56
Show Gist options
  • Save alex-fomin/da2f4173f4400c052368daf658dc389c to your computer and use it in GitHub Desktop.
Save alex-fomin/da2f4173f4400c052368daf658dc389c to your computer and use it in GitHub Desktop.
High DPI plugin - add Retina canvas support to OCanvas
const highDPIPlugin = function () {
const scale = window.devicePixelRatio || 1;
if (scale === 1) {
return;
}
Object.defineProperty(this, "width", {
enumerable: true,
configurable: true,
set(value) {
this.canvasElement.style.width = value + "px";
this.canvasElement.width = value * scale;
this.canvas.scale(scale, scale);
this.background.set(this.settings.background);
this.redraw();
},
get() {
return this.canvasElement.width;
},
});
Object.defineProperty(this, "height", {
enumerable: true,
configurable: true,
set(value) {
this.canvasElement.height = value * scale;
this.canvasElement.style.height = value + "px";
this.canvas.scale(scale, scale);
this.background.set(this.settings.background);
this.redraw();
},
get() {
return this.canvasElement.height;
},
});
// node_modules/ocanvas/src/mouse.js
this.mouse.getPos = function (e: { pageX: number; pageY: number }) {
let canvas = this.core.canvasElement;
let boundingRect = canvas.getBoundingClientRect();
let scaleX = canvas.width / canvas.clientWidth;
let scaleY = canvas.height / canvas.clientHeight;
// Calculate the mouse position relative to the viewport.
// e.clientX exists, but has been incorrect in older versions of webkit.
let clientX = e.pageX - window.pageXOffset;
let clientY = e.pageY - window.pageYOffset;
let x = (scaleX * (clientX - Math.round(boundingRect.left))) / scale;
let y = (scaleY * (clientY - Math.round(boundingRect.top))) / scale;
return { x, y };
};
};
oCanvas.registerPlugin("highDPI", highDPIPlugin);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment