Painting and wrapping a text inside a rectangular area (html5 canvas)
Recently I had a small requirement for a project I am currently working at in my spare time: centralize a text inside a given rectangular area (if I already know the x, y, w, h dimensions of the rectangle).
The main idea was to use the context.measureText(text).width;
method, as it returns the width of the specified text in pixels – exactly what I needed.
Eventually I’ve came up with the following code:
/**
* @param canvas : The canvas object where to draw .
* This object is usually obtained by doing:
* canvas = document.getElementById('canvasId');
* @param x : The x position of the rectangle.
* @param y : The y position of the rectangle.
* @param w : The width of the rectangle.
* @param h : The height of the rectangle.
* @param text : The text we are going to centralize
*/
paint_centered = function(canvas, x, y, w, h, text) {
// The painting properties
// Normally I would write this as an input parameter
var Paint = {
RECTANGLE_STROKE_STYLE : 'black',
RECTANGLE_LINE_WIDTH : 1,
VALUE_FONT : '12px Arial',
VALUE_FILL_STYLE : 'red'
}
// Obtains the context 2d of the canvas
// It may return null
var ctx2d = canvas.getContext('2d');
if (ctx2d) {
// draw rectangular
ctx2d.strokeStyle=Paint.RECTANGLE_STROKE_STYLE;
ctx2d.lineWidth = Paint.RECTANGLE_LINE_WIDTH;
ctx2d.strokeRect(x, y, w, h);
// draw text (this.val)
ctx2d.textBaseline = "middle";
ctx2d.font = Paint.VALUE_FONT;
ctx2d.fillStyle = Paint.VALUE_FILL_STYLE;
// ctx2d.measureText(text).width/2
// returns the text width (given the supplied font) / 2
textX = x+w/2-ctx2d.measureText(text).width/2;
textY = y+h/2;
ctx2d.fillText(text, textX, textY);
} else {
// Do something meaningful
}
}
And I thought it was working perfectly:
window.onload = function() {
// x y w h
canvas = document.getElementById('c1');
paint_centered(canvas, 30, 20, 50, 30, "Test");
paint_centered(canvas, 30, 70, 80, 40, "Centered text doesn't get wrapped");
}