Created
June 8, 2016 08:02
-
-
Save lgh06/9901ecfcb1010b363b095e73ed9a67a7 to your computer and use it in GitHub Desktop.
canvas on a retina display fix.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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