Reputation: 155
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!
Upvotes: 0
Views: 753
Reputation: 76
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().
Upvotes: 0
Reputation: 313
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);
Upvotes: 1