Skip to content

Instantly share code, notes, and snippets.

@lgh06
Created June 8, 2016 08:02
Show Gist options
  • Save lgh06/9901ecfcb1010b363b095e73ed9a67a7 to your computer and use it in GitHub Desktop.
Save lgh06/9901ecfcb1010b363b095e73ed9a67a7 to your computer and use it in GitHub Desktop.
canvas on a retina display fix.
document.addEventListener("DOMContentLoaded", function(event) {
mycanvas();
});
function mycanvas(){
var ratio = window.devicePixelRatio || 1,
canvas = document.querySelector('canvas'),
context = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
retinaCanvas(canvas,context,ratio);
for (var i = 0; i <= 100; i++) {
context.beginPath();
context.moveTo(Math.random()*width,Math.random()*height);
context.lineTo(Math.random()*width,Math.random()*height);
context.stroke()
}
}
function retinaCanvas(canvas,context,ratio){
if (ratio > 1) {
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
canvas.width = canvasWidth * ratio;
canvas.height = canvasHeight * ratio;
canvas.style.width = canvasWidth + 'px';
canvas.style.height = canvasHeight + 'px';
context.scale(ratio, ratio);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment