Created
December 6, 2011 09:17
-
-
Save chrillo/1437511 to your computer and use it in GitHub Desktop.
Creates a dpi agnostic html canvas for high res images for mobile phones like iphone 4 retina display
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
/* | |
This method creates a html canvas and automatically scales it fit the mobile devices display dpi. You can code everything for 320 px and it still looks pixel perfect on high res displays like iPhone 4 or newer Android devices. | |
iPhone 3Gs has 320 x 480 devicePixelRatio = 1, Android phone has 480 x 800 devicePixelRatio=1.5, iPhone 4 has 480 x 960 devicePixelRatio = 2 | |
code like this creates a circle of the same size on all devices without pixeling | |
*/ | |
var canvas=newCanvas(40,40) | |
ctx=canvas.getContext("2d") | |
ctx.beginPath() | |
ctx.fillStyle="#900" | |
ctx.arc(20,20,10,0,Math.Pi*2,true) | |
ctx.fill() | |
ctx.closePath(); | |
var newCanvas=function(width,height){ | |
var scale=window.devicePixelRatio,canvas,ctx; | |
canvas=document.createElement('canvas'); | |
canvas.width=width; | |
canvas.height=height; | |
canvas.style.width=width+"px"; | |
canvas.style.height=height+"px"; | |
canvas.setAttribute('width', canvas.getAttribute('width')*scale); | |
canvas.setAttribute('height', canvas.getAttribute('height')*scale); | |
ctx=canvas.getContext('2d'); | |
ctx.scale(scale, scale); | |
return canvas | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
didn't work for me i was trying to use this in android but no success my image is still distorted