Skip to content

Instantly share code, notes, and snippets.

@chrillo
Created December 6, 2011 09:17
Show Gist options
  • Save chrillo/1437511 to your computer and use it in GitHub Desktop.
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 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
}
@atulchaudhary
Copy link

didn't work for me i was trying to use this in android but no success my image is still distorted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment