Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
HTML5 Canvas Font Size Based on Canvas Size
When working with HTML5 Canvas, you often need to scale font sizes dynamically based on the canvas dimensions to maintain proportional text across different screen sizes.
The Problem
Fixed font sizes don't adapt when canvas dimensions change, making text too small on large canvases or too large on small ones.
Solution: Proportional Font Scaling
Use a ratio-based approach to calculate font size relative to canvas width:
var fontBase = 800; // Base canvas width
var fontSize = 60; // Desired font size at base width
function getFont(canvas) {
var ratio = fontSize / fontBase;
var scaledSize = canvas.width * ratio;
return Math.floor(scaledSize) + 'px sans-serif';
}
Complete Example
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var fontBase = 800;
var fontSize = 60;
function getFont(canvas) {
var ratio = fontSize / fontBase;
var scaledSize = canvas.width * ratio;
return Math.floor(scaledSize) + 'px sans-serif';
}
// Apply scaled font
ctx.font = getFont(canvas);
ctx.fillText('Scaled Text', 50, 100);
console.log('Canvas width: ' + canvas.width + 'px');
console.log('Calculated font: ' + getFont(canvas));
</script>
Canvas width: 400px Calculated font: 30px sans-serif
How It Works
The formula calculates: scaledFontSize = (canvasWidth / baseWidth) × baseFontSize
- fontBase (800px): Reference canvas width
- fontSize (60px): Desired font size at reference width
- ratio: Proportion of base font to base canvas width
- Math.floor(): Ensures integer pixel values
Multiple Canvas Sizes Example
<canvas id="small" width="200" height="100"></canvas>
<canvas id="medium" width="600" height="200"></canvas>
<canvas id="large" width="1000" height="300"></canvas>
<script>
function setupCanvas(canvasId) {
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext('2d');
var fontBase = 800;
var fontSize = 60;
function getFont(canvas) {
var ratio = fontSize / fontBase;
var scaledSize = canvas.width * ratio;
return Math.floor(scaledSize) + 'px sans-serif';
}
ctx.font = getFont(canvas);
ctx.fillText('Sample Text', 20, 50);
console.log(canvasId + ' - Width: ' + canvas.width + 'px, Font: ' + getFont(canvas));
}
setupCanvas('small');
setupCanvas('medium');
setupCanvas('large');
</script>
small - Width: 200px, Font: 15px sans-serif medium - Width: 600px, Font: 45px sans-serif large - Width: 1000px, Font: 75px sans-serif
Conclusion
Ratio-based font scaling ensures text remains proportional across different canvas sizes. Use fontSize / fontBase * canvasWidth to calculate scalable font sizes for responsive canvas applications.
Advertisements
