I want to center "My TEXT!" no matter the length of the string... As the length of the text gets longer, the x coordinate needs to get less.
How can I get the x length of a string?
<html>
<head>
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, 0, 0);
context.font = "12pt Arial";
context.fillText("My TEXT!", 20, 20);
};
imageObj.src = "http://images.google.com/intl/en_ALL/images/srpr/logo11w.png";
};
</script>
</head>
<body>
<canvas width="282px" height="177px" id="myCanvas"></canvas>
</body>
</html>
Simply add this to your code:
imageObj.onload = function(){
context.drawImage(imageObj, 0, 0);
context.font = "12pt Arial";
/// set text alignment to center
context.textAlign = 'center';
/// draw from center
context.fillText("My TEXT!", canvas.width * 0.5, 20);
};
If you need to get the x coordinate itself you'd need to calculate it based on the width of the text (after the font is set):
var width = context.measureText(myText).width;
var x = (canvas.width - width) * 0.5;
Try setting the text alignment.
context.textAlign = "center";
context.fillText("My LONGGGGG TEXT!", (canvas.width)/2, 20);
This should be what you are looking for. http://www.html5canvastutorials.com/tutorials/html5-canvas-text-align/
There's a textAlign property on canvas that you can set to "center". Then start the fill text in the exact middle of the canvas.
EDIT - Here's a fiddle http://jsfiddle.net/mlienau/2MnnC/
Related
I have a canvas and I want to print words on it in horizontal and vertical orientation. The printing itself works fine but I have a somewhat annoying spacing at the beginning of the words, which becomes extremely visible on the vertical text like the EX on the example image.
I just created a little example which shows what I mean
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create a red line in position 150
ctx.strokeStyle = "red";
ctx.moveTo(150, 20);
ctx.lineTo(150, 170);
ctx.stroke();
ctx.font = "50px Arial";
// Show the different textAlign values
ctx.textAlign = "start";
ctx.fillText("EX", 150, 50);
ctx.textAlign = "end";
ctx.fillText("EX", 150, 100);
ctx.textAlign = "center";
ctx.fillText("EX", 150, 150);
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Is there a way to place the beginning of the word at the point I am drawing to or is there a way to calculate the spacing at the beginning and then just subtract it from the starting point of the text?
The TextMetrics interface has actualBoundingBox[...] information that you can use to know by how much the actual bounding box is offset relatively to the textAlign and textBaseline lines.
So adding the measured actualBoundingBoxLeft to your horizontal position when writing LTR text with the "start" text-align will remove this gap.
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const input = document.querySelector("input");
input.oninput = draw;
draw();
function draw() {
const txt = input.value;
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
// Create a red line in position 150
ctx.strokeStyle = "red";
ctx.moveTo(150, 20);
ctx.lineTo(150, 180);
ctx.stroke();
ctx.font = "50px Arial";
ctx.textBaseline = "top"; // needed for the ascent and decsent measurements
// Show the original textAlign
ctx.textAlign = "start";
ctx.fillText(txt, 150, 30);
// fixed
ctx.fillStyle = "green";
const metrics = ctx.measureText(txt);
ctx.fillText(txt, 150 + metrics.actualBoundingBoxLeft, 110);
// Draw the box around our text
ctx.translate( 150, 110 );
const x = 0; // we already did offset by actualBoundingBoxLeft
const y = metrics.actualBoundingBoxAscent * -1;
const width = metrics.actualBoundingBoxRight + metrics.actualBoundingBoxLeft;
const height = metrics.actualBoundingBoxDescent + metrics.actualBoundingBoxAscent;
ctx.strokeRect(x, y, width, height);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
<input value="Éxy"><br>
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;"></canvas>
i have a fixed sized Canvas (850x400px) and when I'm adding text to this canvas, its scaled up in a weird way, and I don't know why.
If I do not set the canvas to a specific height/width, the text appears normal, why is that?
export function addText() {
var canvas = document.getElementById("canvas"); // 850x400px
var ctx = canvas.getContext("2d");
var y = 1 * 20 + 20;
var text = {
text: "ABC",
x: 20,
y: y
};
ctx.font = "40px consolas";
text.width = ctx.measureText(text.text).width;
text.height = 80;
ctx.fillText(text.text, text.x, text.y);
}
This is what the text in the canvas field will look like:
How can I insert text that is scaled just like normal 40px font?
I think you have not specified the width and height of the canvas HTML element itself, try:
addText();
function addText() {
var canvas = document.getElementById("canvas"); // 850x400px
var ctx = canvas.getContext("2d");
var y = 1 * 20 + 20;
var text = {
text: "ABC",
x: 20,
y: y
};
ctx.font = "40px consolas";
text.width = ctx.measureText(text.text).width;
text.height = 80;
ctx.fillText(text.text, text.x, text.y);
}
<canvas id="canvas" width="850" height="400" style="background: red"></canvas>
Update
Another option is to set the width and height programmatically, this will prevent the zooming:
let canvas = document.getElementById("canvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
I used the window width and height, but any other element will do it.
I am working on a PWA, which will be used to conduct surveys, so what I'm doing is,
I'm capturing a snapshot from a video(within the app) and saving it in a canvas, which works fine.
Now I need to add date, time and geo-coordinates on it.
My Javascript code
var video = document.querySelector('video');
var takenPhotosDiv = document.getElementById( "taken-photos" );
var button = document.querySelector('button');
button.onclick = function() {
drawCanvas();
};
var drawCanvas = function(){
var canvas = window.canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.getContext('2d').fillText( "30-08-2017" + " " + "15:25" + " " + "(79.85858454, 17.56852655)", 50, 150 );
takenPhotosDiv.appendChild( canvas );
}
The above code works fine and it does get close to what's being expected, here's the sample output of the above code
The final text-format should look like this (the text bar should be at the bottom of the image and not in the middle and with much bigger font)
PS: I don't just have to display this in the above mentioned format, even need to save and push it on Firebase later.
Edit:
var addTextToCanvas = function( canvas ){
canvas.lineWidth = 2;
canvas.fillStyle = "blue";
canvas.font = "bold 20px sans-serif";
canvas.textBaseline = "bottom";
canvas.fillText( "30-08-2017" + " " + "15:25" + " " + "(79.85858454, 17.56852655)", 0, 100 );
return canvas;
};
I tried this, but the font and font size remained the same.
This function is called from drawCanvas(), just before appending it to div, since it didn't work, I simply added called fillText on the canvas there itself
Edit 2:
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>
And finally, to extract as image the call needs to be made on the canvas element not context (can be confusing):
var dataUrl = canvas.toDataURL(); // saves out PNG image
or for JPEG:
var dataUrl = canvas.toDataURL("image/jpeg", 0.75);
Try this
var canvas = window.canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var text = "30-08-2017\n15:25\n(79.85858454, 17.56852655)";
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText(text, canvas.width/2, canvas.height/2);
I've tried to look for the answer to this everywhere but I don't seem to find it. But I want to move the text created from an input to a specific position in the canvas, say, on the top centre.
The code runs like this: (JSFIDDLE)
<canvas id="canvas" style="background-color: #000" width="800px" height="300px"></canvas>
<input type="text" id="header-text" placeholder="Your Title">
Meanwhile, the js looks like:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
document.getElementById('header-text').addEventListener('keyup', function() {
var stringTitle = document.getElementById('header-text').value;
console.log(stringTitle)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#fff';
ctx.font = 'bold 36px Arial';
ctx.textAlign = 'center';
var text_title = stringTitle;
ctx.fillText(stringTitle, 15, canvas.height / 2 + 35);
});
Is there a way where I can move the text generated to the top centre? Thanks!
Well, you can use math to calculate the right position.
You used:
ctx.fillText(stringTitle, 15, canvas.height / 2 + 35);
so to change the text position to top center you can use something like this:
ctx.fillText(stringTitle, canvas.width/2, canvas.height / 8 + 35);
To have text in top center:
ctx.fillText(stringTitle, canvas.width / 2, 36);
Where 36 is size of your font (height).
If you need more precision while positioning text horizontally, you could use
CanvasRenderingContext2D.measureText().
If I try to draw text to my canvas at the onload event, the text shows up blurry. I draw to the same canvas later via a button click from another function and it's fine. But if I call this function from the button, it's still blurry. Can anybody see something wrong in this code?
window.onload = initCanvasRender;
function initCanvasRender() {
var c = document.getElementById("canvas");
var ctx = c.getContext('2d');
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'black';
ctx.font = '20px Times New Roman';
ctx.fillText('hello...', c.width/2, c.height/2);
}
There may be some problem with the
ctx.fillText('hello...', c.width/2, c.height/2);
Because if you for example set width of the canvas with css then c.width and c.height will be the default size for the canvas which is, 300x150 and not the size defined in css. Try to set two variables for the width and height that are global for your application. E.g
var canvasWidth = 400;
var canvasHeight = 200;
c.width = canvasWidth;
c.height = canvasHeight;
/* ... */
and then later in your code you can use canvasWidth and canvasWeight:
ctx.fillText('hello...', canvasWidth/2, canvasHeight/2);
Take a look at this test: http://jsfiddle.net/EsQfb/7/ it's important to use use the canvas.width and not canvas.style.width in your case.
Take a look at this for more information about this: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width