HTML5 Canvas Text文本居中实例
生活随笔
收集整理的這篇文章主要介紹了
HTML5 Canvas Text文本居中实例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.代碼:
<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;//畫網(wǎng)線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'; //設(shè)置文本的垂直對齊方式 ctx.textAlign = 'center';//設(shè)置文本的水平對齊方式 textMetrics = ctx.measureText(text);drawGrid('lightgray', 10, 10);drawText();drawCenterSquare(); </script>2.顯示結(jié)果:
轉(zhuǎn)載于:https://www.cnblogs.com/tianma3798/p/5563629.html
總結(jié)
以上是生活随笔為你收集整理的HTML5 Canvas Text文本居中实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 教程:给初学的几个小例子(待补充)
- 下一篇: C/C++:Windows cmd 指令