Skip to content

Instantly share code, notes, and snippets.

@joubertnel
Last active July 8, 2023 12:52
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save joubertnel/870190 to your computer and use it in GitHub Desktop.
Save joubertnel/870190 to your computer and use it in GitHub Desktop.
HTML5 Canvas - Rendering of Text on high-DPI screens
<html>
<head>
<script src='http://code.jquery.com/jquery-1.5.1.min.js'></script>
</head>
<body>
<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>
</body>
<script>
$(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);
});
</script>
</html>
@ahbox
Copy link

ahbox commented Jan 1, 2017

Can't apply this method to this canvas: www.arealme.com/coreball/en/ Weird...

@lanzhiheng
Copy link

very useful, Thx

@trendsno
Copy link

Thanks for this info - Questy

@sagargjasani
Copy link

sagargjasani commented Aug 17, 2022

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

http://jsfiddle.net/4JH75

i was looking for something other while i stumbled upon this.... and it freaking worked..... thanks alot...

@M-Abdoon
Copy link

Thank you so much for the information - qiizy

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