canvas循环绘制带背景的标签
项目需求 需绘制带标签的个人名片,直接上代码:
效果图
1.html
1 <canvas id="mDemo" width="283px" height="503px" style="background:#eee;"></canvas>
2.js
1 <script> 2 3 // 数据 4 let labellist = [{ 5 labelcode: "901520002005", 6 labelname: "认真负责" 7 }, 8 { 9 labelcode: "901520002007", 10 labelname: "规划专业" 11 }, 12 { 13 labelcode: "901520002015", 14 labelname: "亲切随和" 15 } 16 ]; 17 let startX = 0, 18 startY = 200; 19 20 let canvas_ = document.getElementById('mDemo'); 21 let ctx = canvas_.getContext('2d'); 22 23 let w = canvas_.width, 24 h = canvas_.height; 25 26 labellist.length == 3 ? startX = (w / 2) - 110 : [labellist.length == 2 ? startX = (w / 2) - 70 : startX = (w / 2) - 30]; // 不同标签个数,设置不同的起点startX(根据自己的需求自己设定) 27 for (let i = 0; i < labellist.length; i++) { 28 ((i) => { 29 ctx.font = '12px Microsoft YaHei'; 30 let item = labellist[i].labelname; 31 let width = ctx.measureText(item).width; //字体宽度 32 let coordinates = getDrawArc(ctx, width, 3); 33 ctx.fillStyle = '#fff'; 34 ctx.fillText(item, coordinates[0], coordinates[1]); 35 })(i) 36 } 37 38 // 绘制label背景 39 function getDrawArc(ctx, w, r) { 40 let _this = this; 41 let x = parseFloat(startX + ''); 42 let y = parseFloat(startY + ''); 43 let endX = x + w + 2 * r + 28; //标签之间的间距 44 startX = endX; 45 startY = y; 46 ctx.beginPath(); 47 ctx.moveTo(x + r, y - 32); // 创建开始点 48 ctx.lineTo(x + w + r, y - 32); // 创建水平线 49 50 ctx.strokeStyle = '#FE8A00'; 51 ctx.arcTo(x + w + 2 * r, y - 32, x + w + 2 * r, y + r - 32, r); // 创建弧 //右上 52 53 ctx.arcTo(x + w + 2 * r, y - 10, x + w, y - 10, r); //右下 54 55 ctx.lineTo(x + r, y - 10); 56 57 ctx.arcTo(x, y - 10, x, y + r - 18, r); //左下 58 59 ctx.arcTo(x, y - 32, x + r, y - 32, r); //左上 60 61 ctx.fillStyle = '#FE8A00'; 62 ctx.fill(); 63 ctx.stroke(); 64 ctx.restore(); //恢复状态 65 return [x + r, y + r - 20] 66 } 67 </script>