Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
HTML5 Canvas - Rendering of Text on high-DPI screens
<script src=''></script>
<h2>Naive canvas</h2>
<canvas id="naive" width="400" height="50"></canvas>
<h2>High-def Canvas</h2>
<canvas id="hidef" width="400" height="50"></canvas>
$(document).ready(function() {
// Output to Canvas without consideration of device pixel ratio
var naiveContext = $('#naive')[0].getContext('2d');
naiveContext.font = '16px Palantino';
naiveContext.fillText('Rothko is classified as an abstract expressionist.', 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 = "16px Palantino";
hidefContext.fillText("Rothko is classified as an abstract expressionist.", 10, 20);
Copy link

ddrscott commented Mar 13, 2014

Thanks for the snippet. I converted it to a jsfiddle.

Copy link

Costava commented Apr 17, 2015

On line 39, "Palatino" is misspelled as "Palantino".

I forked the gist and made the change:

Here is the updated jsfiddle:

Copy link

razvanphp commented May 15, 2015

Perfect! Thank you!

Copy link

ahbox commented Jan 1, 2017

Can't apply this method to this canvas: Weird...

Copy link

lanzhiheng commented May 19, 2017

very useful, Thx

Copy link

trendsno commented Feb 26, 2021

Thanks for this info - Questy

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