var canvas = document.getElementById("canvas1"); var context = canvas.getContext("2d"); // fill font context.font = "60px Palatino"; context.fillStyle = "red"; context.fillText("Cancas", 30, 60); // stroke font context.strokeStyle = "yellow"; context.strokeText("Cancas", 30, 60); // back measure object context.fillStyle = "blue"; var measure = context.measureText("Cancas", 30, 120); // print text width console.log(measure.width);
文本垂直方向定位:textBaseline;
var canvas = document.getElementById("canvas2"); var context = canvas.getContext("2d"); function drawBackground() { var STEP_Y = 12, TOP_MARGIN = STEP_Y * 4, LEFT_MARGIN = STEP_Y * 3, i = context.canvas.height; context.strokeStyle = "lightgray"; context.lineWidth = 1; while( i > STEP_Y ) { context.beginPath(); context.moveTo(0, i + 0.5); context.lineTo(context.canvas.width, i + 0.5); context.stroke(); i -= STEP_Y; } context.strokeStyle = "rgba(100, 0, 0, 0.3)"; context.lineWidth = 1; context.beginPath(); context.moveTo(LEFT_MARGIN, 0); context.lineTo(LEFT_MARGIN, context.canvas.height); context.stroke(); } // draw background drawBackground(); // 給文本填充漸變效果 var gradient = context.createLinearGradient(0, 0, canvas.width, canvas.height); gradient.addColorStop(0, "red"); gradient.addColorStop(1, "blue"); context.font = "60px Arial"; context.textAlign = "left"; context.textBaseline = "middle"; context.fillStyle = gradient; context.fillText("CANVAS", 60, 60); context.strokeStyle = "red"; context.beginPath(); context.moveTo(0.5, 60); context.lineTo(canvas.width+0.5, 60); context.stroke();
在圓弧周圍繪制文本
var canvas = document.getElementById("canvas3"); var context = canvas.getContext("2d"); // 圓弧的屬性,圓弧的坐標及圓弧的半徑// var circle = { x: canvas.width/2, y: canvas.height/2, radius:200 } function drawCircularText(string, startAngle, endAngle) { var radius = circle.radius,//圓弧半徑 angleDecrement = (startAngle - endAngle)/(string.length - 1),//計算出第一個字符所占有的弧度 angle = parseFloat( startAngle ),//將弧度轉換浮點型 index = 0,//在canvas中繪制到第幾個字符的索引 character;//把當前繪制的字符賦予它 // 保存當前繪圖環境(canvas的屬性、剪輯區域、translate) context.save(); context.fillStyle = "red"; context.strokeStyle = "blue"; context.font = "20px Lucida Sans"; while ( index < string.length ) { // 獲取當前要繪制的字符 character = string.charAt(index); // 保存當前之前的環境增狀態 context.save(); // 清除當前路徑的子路徑 context.beginPath(); // 位移 context.translate(circle.x + Math.cos(angle) * radius, circle.y - Math.sin(angle) * radius); // 旋轉弧度 context.rotate(Math.PI/2 - angle); // 填充文本 context.fillText(character, 0, 0); // 描邊文本 context.strokeText( character, 0, 0); // 重新計算下一個字符的弧度 angle -= angleDecrement; // 獲取下一個字符的索引 index++; // 還原上次save()狀態 context.restore(); } context.restore(); } drawCircularText("canvas's hello word canvas's hello word", Math.PI*2, Math.PI / 8);