2016-08-30 72 views
0

我試圖尋找各處的答案,但我似乎找不到它。但是我想將從輸入創建的文本移動到畫布中的特定位置,比如頂部中心。將畫布元素移動到所需的位置

代碼運行是這樣的:(JSFIDDLE

<canvas id="canvas" style="background-color: #000" width="800px" height="300px"></canvas> 

<input type="text" id="header-text" placeholder="Your Title"> 

同時,JS是這樣的:

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

有沒有一種方法,我可以移動產生的頂端中央的文字?謝謝!

回答

1

那麼,你可以使用數學來計算正確的位置。 您使用:

ctx.fillText(stringTitle, 15, canvas.height/2 + 35); 

所以對文本位置改變到頂部中心,您可以使用這樣的事情:

ctx.fillText(stringTitle, canvas.width/2, canvas.height/8 + 35); 
+0

工作!謝謝! –

+0

哎唷!使用硬編碼的y偏移量(甚至基於字體大小的y偏移量)並不十分精確。相反,使用'context.setBaseline'是爲了實現垂直對齊文本的目的。 – markE

+0

你說得對。你的回答比較好,我的不好。我仍然在學習JS;) –

0

要在頂部中央的文字:

ctx.fillText(stringTitle, canvas.width/2, 36);

哪裏36是你的字體(高度)的大小。 如果在水平定位文本時需要更高精度,則可以使用 CanvasRenderingContext2D.measureText()