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,否則測量寬度不準確。