typescript重写canvas --12.文字字体
1.使用 canvas 文字字体
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<canvas id="myCanvas" width="600" height="400">
你的浏览器不支持HTML5
</canvas>
<script type="text/javascript">
var canvas=document.getElementById("myCanvas");
var context=canvas.getContext("2d");
context.beginPath();
//设定文字字体为Arial
context.font="30px Arial";
context.fillText("Hello World (Arial)",50,50);
context.beginPath();
//设定文字字体为Verdana
context.font="30px Verdana";
context.fillText("Hello World (Verdana)",50,100);
context.beginPath();
//设定文字字体为Times New Roman
context.font="30px Times New Roman";
context.fillText("Hello World (Times New Roman)",50,150);
context.beginPath();
//设定文字字体为Courier New
context.font="30px Courier New";
context.fillText("Hello World (Courier New)",50,200);
context.beginPath();
//设定文字字体为serif
context.font="30px serif";
context.fillText("Hello World (serif)",50,250);
context.beginPath();
//设定文字字体为sans-serif
context.font="30px sans-serif";
context.fillText("Hello World (sans-serif)",50,300);
</script>
</body>
</html>
显示效果如下

2.typescript重写canvas --文字大小
html文件
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="600" height="400">
你的浏览器不支持HTML5
</canvas>
<script src="./js/12.js"></script>
</body>
</html>
ts文件
const canvas=<HTMLCanvasElement>document.getElementById("myCanvas")
const context=canvas.getContext("2d")
if (context){
context.beginPath();
//设定文字字体为Arial
context.font="30px Arial";
context.fillText("Hello World (Arial)",50,50);
context.beginPath();
//设定文字字体为Verdana
context.font="30px Verdana";
context.fillText("Hello World (Verdana)",50,100);
context.beginPath();
//设定文字字体为Times New Roman
context.font="30px Times New Roman";
context.fillText("Hello World (Times New Roman)",50,150);
context.beginPath();
//设定文字字体为Courier New
context.font="30px Courier New";
context.fillText("Hello World (Courier New)",50,200);
context.beginPath();
//设定文字字体为serif
context.font="30px serif";
context.fillText("Hello World (serif)",50,250);
context.beginPath();
//设定文字字体为sans-serif
context.font="30px sans-serif";
context.fillText("Hello World (sans-serif)",50,300);
}
生成的js文件
"use strict";
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");
if (context) {
context.beginPath();
//设定文字字体为Arial
context.font="30px Arial";
context.fillText("Hello World (Arial)",50,50);
context.beginPath();
//设定文字字体为Verdana
context.font="30px Verdana";
context.fillText("Hello World (Verdana)",50,100);
context.beginPath();
//设定文字字体为Times New Roman
context.font="30px Times New Roman";
context.fillText("Hello World (Times New Roman)",50,150);
context.beginPath();
//设定文字字体为Courier New
context.font="30px Courier New";
context.fillText("Hello World (Courier New)",50,200);
context.beginPath();
//设定文字字体为serif
context.font="30px serif";
context.fillText("Hello World (serif)",50,250);
context.beginPath();
//设定文字字体为sans-serif
context.font="30px sans-serif";
context.fillText("Hello World (sans-serif)",50,300);
}