返回到:Canvas API:CanvasRenderingContext2D
CanvasRenderingContext2D.font
是 Canvas 2D API 描述绘制文字时,当前字体样式的属性。使用和 CSS font 规范相同的字符串值。
语法
ctx.font = value;
选项
value
符合 CSS font
语法的DOMString
字符串。默认字体是 10px sans-serif。
示例
使用自定义字体
这个例子使用 font
属性设置了不同的字体大小和字体种类。
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "bold 48px serif";
ctx.strokeText("Hello world", 50, 100);
看下DEMO:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>CanvasRenderingContext2D.font | Web176教程www.web176.com</title> <meta name="robots" content="noindex, nofollow"> <style> body { padding: 0; margin: 0; } svg:not(:root) { display: block; } .playable-code { background-color: #f4f7f8; border: none; border-left: 6px solid #558abb; border-width: medium medium medium 6px; color: #4d4e53; height: 100px; width: 90%; padding: 10px 10px 0; } .playable-canvas { border: 1px solid #4d4e53; border-radius: 2px; } .playable-buttons { text-align: right; width: 90%; padding: 5px 10px 5px 26px; } </style> </head> <body> <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="编辑" /> <input id="reset" type="button" value="重置" /> </div> <textarea id="code" class="playable-code"> ctx.font = "bold 48px serif"; ctx.strokeText("Hello world", 50, 100);</textarea> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code; drawCanvas(); }); edit.addEventListener("click", function() { textarea.focus(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas); </script> </body> </html>
使用 CSS 字体加载 API 加载字体
借助FontFace
API 的帮助,您可以在画布中使用字体之前显式加载字体。
let f = new FontFace('test', 'url(x)');
f.load().then(function() {
// Ready to use the font in a canvas context
});
返回到:Canvas API:CanvasRenderingContext2D
作者:terry,如若转载,请注明出处:https://www.web176.com/canvas_api/7952.html