最急在工作中遇到一个需求,根据给定的编码生成编码说明,像下面这样的效果。
预览地址:https://www.huhailong.vip/res/html/codedescribe
/**
* 绘制编码说明图片
* @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 文件如下
<!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>
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%;
}
因为没有找到符合的组件,所以自己写了,如果有知道有现成组件的小伙伴也可以分享一下。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.