1.文本1
demo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas学习</title>
<style>
body{background: black}
#c1{background: white}
span{color: white}
</style>
<script type="text/javascript">
window.onload = function(){
var oC = document.getElementById('c1');
var oGC = oC.getContext('2d');
oGC.font = '60px impact' //注意这块,后面必须指定文字,任意文字都可,如果不想,则写'impact'
oGC.textBaseline = 'top' //文字垂直方向以哪个为基准点 也可以是(middle,bottom)
oGC.fillText('前端学习',0,0) //(文字,坐标x,坐标y)
oGC.strokeText('前端学习',0,200) //空心的字体
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
</body>
</html>
2.文本2
demo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas学习</title>
<style>
body{background: black}
#c1{background: white}
span{color: white}
</style>
<script type="text/javascript">
window.onload = function(){
var oC = document.getElementById('c1');
var oGC = oC.getContext('2d');
oGC.font = '60px impact' //注意这块,后面必须指定文字,任意文字都可,如果不想,则写'impact'
oGC.textBaseline = 'top' //文字垂直方向以哪个为基准点 也可以是(middle,bottom)
var w = oGC.measureText('前端学习').width
// 注意文字的高其实就是文字的大小,也就是60px
oGC.fillText('前端学习',(oC.width-w)/2,(oC.height-60)/2) //(文字,坐标x,坐标y)
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
</body>
</html>
3.阴影
demo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas学习</title>
<style>
body{background: black}
#c1{background: white}
span{color: white}
</style>
<script type="text/javascript">
window.onload = function(){
var oC = document.getElementById('c1');
var oGC = oC.getContext('2d');
oGC.font = '60px impact' //注意这块,后面必须指定文字,任意文字都可,如果不想,则写'impact'
oGC.textBaseline = 'top' //文字垂直方向以哪个为基准点 也可以是(middle,bottom)
oGC.shadowOffsetX = 10
oGC.shadowOffsetY = 20
oGC.shadowBlur = 5
oGC.shadowColor = 'yellow' //默认颜色黑色透明 rgba(0,0,0,0)
var w = oGC.measureText('前端学习').width
// 注意文字的高其实就是文字的大小,也就是60px
oGC.fillText('前端学习',(oC.width-w)/2,(oC.height-60)/2) //(文字,坐标x,坐标y)
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
</body>
</html>