最急在工作中遇到一个需求,根据给定的编码生成编码说明,像下面这样的效果。
不同含义的编码用横杠分割,然后每个编码下面用箭头指明具体的含义。下面是我使用canvas实现的代码。具体的编码宽度大家可以根据实际情况进行调整,目前我的这个方法中支持起始坐标设定,和箭头的长度设定。
预览地址:https://www.huhailong.vip/res/html/codedescribe
javascript
/**
* 绘制编码说明图片
* @param {起始横坐标} startX
* @param {起始纵坐标} startY
* @param {编码信息对象} codeDescribeObj
*/
function drawCode(startX, startY, codeDescribeObj) {
const canvas = document.getElementById('code-canvas');
const ctx = canvas.getContext('2d');
let preTextWidth = startX; //左侧开始坐标
let preTextHeight = startY; //开始高度坐标
for(let i=0; i<codeDescribeObj.codeList.length; i++){
ctx.font = "50px Arial";
let tempText = ctx.measureText(codeDescribeObj.codeList[i]);
ctx.fillText(codeDescribeObj.codeList[i], preTextWidth, preTextHeight);
if(i < codeDescribeObj.codeList.length - 1){
ctx.fillText('---',preTextWidth+tempText.width+10,preTextHeight - 2);
}
ctx.stroke();
ctx.font = "16px Arial";
let describeY = preTextHeight + codeDescribeObj.arrowHeightList[i];
ctx.fillText(codeDescribeObj.describeList[i], preTextWidth, describeY);
ctx.stroke();
//绘制箭头
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(preTextWidth + 30, preTextHeight + 10);
ctx.lineTo(preTextWidth + 30, describeY - 20);
ctx.lineTo(preTextWidth + 25, describeY - 30);
ctx.moveTo(preTextWidth + 30, describeY - 20);
ctx.lineTo(preTextWidth + 35, describeY - 30);
ctx.stroke();
//更新坐标信息
preTextWidth = preTextWidth + tempText.width + 80;
}
}
//定义编码信息对象
const codeDescribeObj = {
codeList: ['F1','YHT','23Y','S1','8R'],
describeList: ['方案代码','颜色代码','年代系列代码','品类款式代码','尺寸方向代码'],
arrowHeightList: [100,300,200,150,300]
}
drawCode(120, 100, codeDescribeObj);
对应的html文件和css文件如下
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>编码说明图片绘制</title>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<div class="box">
<canvas id="code-canvas" width="1000" height="600"></canvas>
</div>
<script src="./index.js"></script>
</body>
</html>
css
body{
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.box{
text-align: center;
width: 800px;
}
canvas{
border: 1px solid gray;
border-radius: 4px;
width: 100%;
}
如果本次分享的代码对你有所帮助,或者觉得不错的话,记得点个大大的赞哦!