Skip to content

Instantly share code, notes, and snippets.

@Decoherence
Last active August 29, 2015 14:06
Show Gist options
  • Save Decoherence/26ea689e33e1049f1ec2 to your computer and use it in GitHub Desktop.
Save Decoherence/26ea689e33e1049f1ec2 to your computer and use it in GitHub Desktop.
HTML5 Canvas HiDPI
<h2>Naive canvas</h2>
<canvas id="naive" width="400" height="50"></canvas>
<h2>High-def Canvas</h2>
<canvas id="hidef" width="800" height="500"></canvas>
$(document).ready(function () {
// Output to Canvas without consideration of device pixel ratio
var naiveContext = $('#naive')[0].getContext('2d');
naiveContext.font = '16px Palatino';
naiveContext.fillText('These pixels need some work.', 10, 20);
// Output to Canvas, taking into account devices such as iPhone 4 with Retina Display
var hidefCanvas = $('#hidef')[0];
var hidefContext = hidefCanvas.getContext('2d');
if (window.devicePixelRatio) {
var hidefCanvasWidth = $(hidefCanvas).attr('width');
var hidefCanvasHeight = $(hidefCanvas).attr('height');
var hidefCanvasCssWidth = hidefCanvasWidth;
var hidefCanvasCssHeight = hidefCanvasHeight;
$(hidefCanvas).attr('width', hidefCanvasWidth * window.devicePixelRatio);
$(hidefCanvas).attr('height', hidefCanvasHeight * window.devicePixelRatio);
$(hidefCanvas).css('width', hidefCanvasCssWidth);
$(hidefCanvas).css('height', hidefCanvasCssHeight);
hidefContext.scale(window.devicePixelRatio, window.devicePixelRatio);
}
hidefContext.font = "30px Serif";
hidefContext.fillText("These pixels are pretty.", 10, 20);
hidefContext.beginPath();
hidefContext.rect(188, 50, 200, 100);
hidefContext.fillStyle = 'yellow';
hidefContext.fill();
hidefContext.lineWidth = 7;
hidefContext.strokeStyle = 'black';
hidefContext.stroke();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment