日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

HTML5 Canvas Text文本居中实例

發(fā)布時(shí)間:2025/3/20 HTML 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HTML5 Canvas Text文本居中实例 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。