首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

HTML5 Canvas 文字繪製全攻略:填充、描邊、度量與圓弧排版

     編輯:關於C語言

Canvas 文字三大方法

  • fillText(text, x, y):繪製填充文字。
  • strokeText(text, x, y):繪製描邊文字。
  • measureText(text):返回包含 width 屬性的對象,表示文字寬度。

文字三大屬性

  • font:如 "60px Palatino"。
  • textAlign:start|end|left|right|center。
  • textBaseline:top|hanging|middle|alphabetic|ideographic|bottom。

基本範例

<canvas id="c1" width="300" height="150"></canvas>
<script>
var ctx = document.getElementById('c1').getContext('2d');
ctx.font = '60px Palatino';
ctx.fillStyle = 'red';
ctx.fillText('Canvas', 30, 60);
ctx.strokeStyle = 'yellow';
ctx.strokeText('Canvas', 30, 60);
var m = ctx.measureText('Canvas');
console.log('寬度:', m.width);
</script>

漸變填充與基線對齊

var gradient = ctx.createLinearGradient(0,0,500,300);
gradient.addColorStop(0,'red'); gradient.addColorStop(1,'blue');
ctx.font = '60px Arial';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillStyle = gradient;
ctx.fillText('CANVAS', 60, 60);
// 畫基線輔助線
ctx.strokeStyle = 'red';
ctx.beginPath(); ctx.moveTo(0.5,60); ctx.lineTo(500.5,60); ctx.stroke();

圓弧路徑排版文字

function drawCircularText(str, startAng, endAng) {
    var R = 200, cx = 250, cy = 250;
    var delta = (startAng - endAng) / (str.length - 1);
    var ang = startAng;
    ctx.save();
    ctx.fillStyle = 'red'; ctx.strokeStyle = 'blue'; ctx.font = '20px Lucida Sans';
    for (var i=0; i<str.length; i++) {
        ctx.save();
        ctx.beginPath();
        var x = cx + Math.cos(ang) * R;
        var y = cy - Math.sin(ang) * R;
        ctx.translate(x, y);
        ctx.rotate(Math.PI/2 - ang);
        ctx.fillText(str[i], 0, 0);
        ctx.strokeText(str[i], 0, 0);
        ctx.restore();
        ang -= delta;
    }
    ctx.restore();
}
drawCircularText("Canvas Hello World", Math.PI*2, Math.PI/8);

注意事項

必須在調用 measureText 前設置好 font,否則測量寬度不準確。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved