How to Write Text on a HTML5 Canvas Element

How can I write text on a HTML5 canvas element?

var canvas = document.getElementById("my-canvas");
var context = canvas.getContext("2d");

context.fillStyle = "blue";
context.font = "bold 16px Arial";
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText("Zibri", (canvas.width / 2), (canvas.height / 2));
#my-canvas {
background: #FF0;
}
<canvas id="my-canvas" width="200" height="120"></canvas>

Trying to add text in canvas

Make sure that the methods and properties are set on the context not the canvas element itself.

We also need to calculate the actual vertical position of the text. Since it's aligned to the bottom we can use the height of the canvas minus some bottom padding:

var y = canvas.height - 10;

So, for example:

var addTextToCanvas = function( context ) { // pass in 2D context
var y = context.canvas.height - 10;
context.fillStyle = "blue";
context.font = "bold 20px sans-serif";
context.textBaseline = "bottom";
context.fillText( "30-08-2017"+" "+"15:25"+" "+"(79.85858454, 17.56852655)", 10, y );
return context;
};

or if you prefer to pass in the canvas:

var addTextToCanvas = function( canvas ) {
var context = canvas.getContext("2d");
var y = canvas.height - 10;
context.fillStyle = "blue";
context.font = "bold 20px sans-serif";
context.textBaseline = "bottom";
context.fillText( "30-08-2017"+" "+"15:25"+" "+"(79.85858454, 17.56852655)", 10, y );
return context;
};

The lineWidth doesn't do anything here so it can be removed.

I would recommend that you store the context once globally. It's the same context you get each time anyways but there is more overhead requesting it each time it will be used.

Functional example:

var ctx = c.getContext("2d");
var addTextToCanvas = function( context ) { context.fillStyle = "blue"; context.font = "bold 20px sans-serif"; context.textBaseline = "bottom"; var y = context.canvas.height - 10; context.fillText( "30-08-2017"+" "+"15:25"+" "+"(79.85858454, 17.56852655)", 10, y ); return context; };
addTextToCanvas(ctx);
#c {border: 1px solid #999}
<canvas id=c width=600 height=180></canvas>

Add text to element drawn using HTML canvas

Centering text on a point can be done with textAlign = 'center'. Once you have it centered you can use translate and rotate to position the text where you want it. The following snippet is very static so if your map is going to be large with lots of points and names you may want to create a function that takes in the points and determines the angle of each line and then passes that angle to the rotate method.

The angle of a line can be found with atan2. Once you have that you can rotate the text to the exact angle of the line. Everything below can be written to be more dynamic but gives you an idea of how you can achieve what you want.

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;

class Map {
constructor(x, y, name) {
this.x = x;
this.y = y;
this.name = name;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.font = "12px arial";
ctx.textAlign = "center";
ctx.fillText(this.name, this.x, this.y - 10);
}
}
let locations = [];
let california = locations.push(new Map(30, 200, "California"));
let oregon = locations.push(new Map(50, 100, "Oregon"));
let washington = locations.push(new Map(50, 25, "Washington"));
let nevada = locations.push(new Map(150, 180, "Nevada"));
let utah = locations.push(new Map(210, 170, "Utah"));
let arizona = locations.push(new Map(200, 230, "Arizona"));

function drawLocations() {
for (let i = 0; i < locations.length; i++) {
locations[i].draw();
}
}
drawLocations();

class Roads {
constructor(x1, y1, x2, y2, name) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.name = name;
}
draw() {
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(this.x1, this.y1);
ctx.lineTo(this.x2, this.y2);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
let roads = [];
let CA_OR = roads.push(
new Roads(
locations[0].x,
locations[0].y,
locations[1].x,
locations[1].y,
"HWY1"
)
);
let OR_WA = roads.push(
new Roads(
locations[1].x,
locations[1].y,
locations[2].x,
locations[2].y,
"HWY1"
)
);
let CA_NV = roads.push(
new Roads(
locations[0].x,
locations[0].y,
locations[3].x,
locations[3].y,
"I80"
)
);
let NV_UT = roads.push(
new Roads(
locations[3].x,
locations[3].y,
locations[4].x,
locations[4].y,
"I80"
)
);
let UT_CO = roads.push(
new Roads(
locations[4].x,
locations[4].y,
locations[5].x,
locations[5].y,
"I15"
)
);

function drawRoads() {
for (let i = 0; i < roads.length; i++) {
roads[i].draw();
getAngle(roads[i], roads[i].name);
}
}
drawRoads();

function drawNames(ang, x1, y1, name) {
ctx.font = "10px arial";
ctx.textAlign = "center";
ctx.save();
ctx.translate(x1, y1);
ctx.rotate(ang);
if (name == "I15") {
ctx.rotate(-ang);
}
if (name == "I80") {
ctx.fillText(name, 0, 15);
} else if (name == "I15") {
ctx.fillText(name, 15, 0);
} else {
ctx.fillText(name, 0, -5);
}
ctx.restore();
}

function getAngle(roads, name) {
let dx = roads.x1 - roads.x2;
let dy = roads.y1 - roads.y2;
let midX = roads.x1 + (roads.x2 - roads.x1) * 0.5;
let midY = roads.y1 + (roads.y2 - roads.y1) * 0.5;
drawNames(Math.atan2(-dy, -dx), midX, midY, name);
}
<canvas id="canvas"></canvas>

How do I add text above a HTML5 canvas?

Two things you'll benefit from knowing about:

  • Positioning. In CSS, you can position things 'absolutely', so that things can stack one on top of the other

  • z-index. z-index helps the browser understand how you want stacked items to layer; if the <p> tag has a higher z-index than the canvas, it'll be shown over the canvas, and vice versa.


Further reading:

https://developer.mozilla.org/en/docs/Web/CSS/position
https://developer.mozilla.org/en/docs/Web/CSS/z-index

Allowing the user to type text in a HTML5 Canvas game

You can get a floating HTML element on the top of canvas using the following CSS technique.

http://css-tricks.com/absolute-positioning-inside-relative-positioning/

  • Make a wrapper div position: relative

  • Add canvas inside using position: absolute

  • Add other HTML controls inside using position: absolute

This applies for all HTML elements, not just canvas.

How do you put text to the right or left of a canvas element?

Not sure how much content you would like to add on the left/right of the canvas element but I would suggest something like:

<div class="container">
<div>Left text....</div>
<canvas id="canvas" width="700" height="700"></canvas>
<div>Right text....</div>
</div>

With the following CSS:

.container {display: flex; flex-direction: "row"; }

Add text over canvas chart javascript

in the Doughnut chart definition, i added the following:

  Chart.pluginService.register({
beforeDraw: function(chart) {
if(chart.chart.config.type=="doughnut" && chart.canvas.id=="position01"){

chart.clear();
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;

// ctx.restore();
var fontSize = (height / 200).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";

var sum = 0;
input.data.map(p=>sum+=p);
var ductCostText = "Ducts Cost:" ;//was like that: textX = Math.round((width - ctx.measureText(text).width) / 2),
var costText = numberWithCommas(sum.toFixed(2)*200) + "₪";
textX = 0;// Xcoordinate for the text
textY = height / 2-120;// the Y coordinant of the cost header

ctx.fillText(ductCostText, textX, textY);


}

}
});
// formatting function : format as a price
function numberWithCommas(x) {
return x.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

How to write text on top of image in HTML5 canvas?

That is because you draw the text before the image has loaded and been drawn. You have to draw the text that should be on top of the image after the image is drawn. Try this code instead:

window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, 10, 10);
context.font = "40pt Calibri";
context.fillText("My TEXT!", 20, 20);
};
imageObj.src = "darth-vader.jpg";
};

Example:

Sample Image



Related Topics



Leave a reply



Submit