Rudolph Musngi Rudolph Musngi - 5 months ago 21
CSS Question

Move canvas element into desired position

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;

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);