HTML5 Canvas Text文本居中实例
2016-06-06 13:59
561 查看
1.代码:
2.显示结果:
<canvas width="700" height="300" id="canvasOne" class="canvasOne"></canvas> <script> var cancasOne = document.getElementById('canvasOne'); var ctx = cancasOne.getContext('2d'); var text = '后会无期', textMetrics, square_width = 20, font_height = 128; //画网线 function drawGrid(color, stepx, stepy) { ctx.save(); ctx.strokeStyle = color; ctx.lineWidth = 0.5; ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvasOne.width, canvasOne.height); //画竖线 for (var i = stepx + 0.5; i < canvasOne.width; i += stepx) { ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, canvasOne.height); ctx.stroke(); } //画横线 for (var i = stepx + 0.5; i < canvasOne.height; i += stepy) { ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(canvasOne.width, i); ctx.stroke(); } ctx.restore(); } //画文本 function drawText() { ctx.fillStyle = 'orange'; ctx.strokeStyle = 'cornflowerblue'; ctx.fillText(text, canvasOne.width / 2, canvasOne.height / 2); ctx.strokeText(text, canvasOne.width / 2, cancasOne.height / 2); } //画中间的小正方形 function drawCenterSquare() { ctx.fillStyle = 'rgba(255,0,0,0.4)'; ctx.strokeStyle = 'black'; ctx.fillRect(canvasOne.width / 2 - square_width / 2, canvasOne.height / 2 - square_width / 2, square_width, square_width); ctx.strokeRect(canvasOne.width / 2 - square_width / 2, cancasOne.height / 2 - square_width / 2, square_width, square_width); } ctx.font = '128px Helvetica'; ctx.textBaseline = 'middle'; //设置文本的垂直对齐方式 ctx.textAlign = 'center';//设置文本的水平对齐方式 textMetrics = ctx.measureText(text); drawGrid('lightgray', 10, 10); drawText(); drawCenterSquare(); </script>
2.显示结果:
相关文章推荐
- 手机访问智能硬件的三种模式
- HTML5 Canvas Text实例1
- h5 缓存
- Html5 Canvas Text
- HTML5屏幕适配标签设置
- H5中的标记方法
- html5 拖放事件
- Web前端初步——HTML5
- 10个最常见的HTML5面试题 附答案
- HTML5之触摸事件(touchstart、touchmove和touchend)
- 自学HTML5第一步--IDEA的下载与安装
- 每天15min-HTML5(3)-文本标签
- 前端开发攻城师绝对不可忽视的五个HTML5新特性
- 端午H5游戏反思
- html&&html5(3)
- h5新增表单控件及其相关属性
- html&&html5(2)
- html&&html5(1)
- HTML5笔记:跨域通讯、多线程、本地存储和多图片上传技术(转)
- HTML5学习笔记-基础篇2-新元素概览