canvas实现文字圆形排列的方法
dearweb 发布:2021-10-21 15:07:06阅读:canvas结合js实现文字圆形排列的方法;
效果预览
代码展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <canvas id="canvas" width="300" height="300" data-total="100" data-curr="75" ></canvas> <script> var canvas = document.getElementById('canvas') var ctx = canvas.getContext('2d') console.log(canvas.getContext) //转换弧度 function rads(x) { return (Math.PI * x) / 180 } function drawCircularText(s, string, startAngle, endAngle) { var radius = s.radius, angleDecrement = (startAngle - endAngle) / (string.length - 1), angle = parseFloat(startAngle), index = 0, character ctx.save() ctx.fillStyle = 'black' ctx.font = '30px 微软雅黑' ctx.textAlign = 'right' ctx.textBaseline = 'middle' while (index < string.length) { character = string.charAt(index) ctx.save() ctx.beginPath() ctx.translate( s.x + Math.cos(angle) * radius, s.y + Math.sin(angle) * radius ) ctx.rotate(Math.PI / 2 + angle) ctx.fillText(character, 0, 0) angle -= angleDecrement index++ ctx.restore() } ctx.restore() } ctx.textAlign = 'center' ctx.textBaseLine = 'middle' if (canvas.getContext) { var circle = { x: 150, y: 150, radius: 100, } drawCircularText(circle, '123456', Math.PI * 2, Math.PI / 3) } //第三个参数表示文字首位是否相接 差了多少弧度 </script> </body> </html>
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧