为了账号安全,请及时绑定邮箱和手机立即绑定

怎么根据json的数据坐标,动态赋值给canvas绘制矩形

怎么根据json的数据坐标,动态赋值给canvas绘制矩形

POPMUISE 2019-05-12 09:07:49
以下完整代码,我现在写死的一个json,里面boundingBox对应的是四个角坐标,怎么把那四个坐标解析出来,并赋值给下面canvas绘制矩形的四个点,这样后台给不同的json坐标,画不同的矩形。canvas要封装成函数吗?我看网上封装的canvas矩形都是填充宽高的,不是坐标,该怎么写呢?Document身份证识别适用于身份证、票据和证件识别等多应用场景……本地上传文本内容序号识别文字结果位置信息左上角右上角右下角左上角JSON$(function(){$('#chooseImage').on('change',function(){varfile=this.files[0];varimage=newImage();image.src=URL.createObjectURL(file);image.onload=function(){varcanvas=document.querySelector("#cvs");varctx=canvas.getContext("2d");canvas.width=image.width;//设置canvas的画布宽度为图片宽度canvas.height=image.height;ctx.drawImage(image,0,0,image.width,image.height)//在canvas上绘制图片//letdataUrl=canvas.toDataURL(image,0.92)//0.92为压缩比,可根据需要设置,设置过小会影响图片质量ctx.strokeStyle="red";varjson={"orientation":"UP","errorCode":"0","lines":[{"boundingBox":"48,58,188,59,187,88,48,87","words":"姓名网小易"},{"boundingBox":"47,106,264,106,263,134,46,134","words":"性别男民族汉"},{"boundingBox":"46,152,328,151,327,177,45,178","words":"出199706月01日"},{"boundingBox":"44,195,371,195,371,224,43,224","words":"住址北京市海淀区西北旺东路10"},{"boundingBox":"109,224,364,224,363,253,109,253","words":"号院中关村软件园西区7号"},{"boundingBox":"47,315,535,316,534,343,46,342","words":"公民身份证号码110101199706010022"}]}varobj=eval(json);for(vari=0;i
查看完整描述

2 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

functiondraw(data){
varcanvas=document.querySelector("#cvs");
varctx=canvas.getContext("2d");
canvas.width=image.width;//设置canvas的画布宽度为图片宽度
canvas.height=image.height;
ctx.drawImage(image,0,0,image.width,image.height)//在canvas上绘制图片
//letdataUrl=canvas.toDataURL(image,0.92)//0.92为压缩比,可根据需要设置,设置过小会影响图片质量
ctx.strokeStyle="red";
varobj=eval(data);
for(vari=0;iconstpoints=obj.lines[i].boundingBox.split(',');
constwords=obj.lines[i].words;
ctx.moveTo(points[0],points[1]);
ctx.lineTo(points[2],points[3]);
ctx.lineTo(points[4],points[5]);
ctx.lineTo(points[6],points[7]);
//fillText
ctx.fillText(words,10,50);//这个坐标根据需求来就好了
}
ctx.closePath();
ctx.stroke();
}
varjson={
"orientation":"UP",
"errorCode":"0",
"lines":[
{
"boundingBox":"48,58,188,59,187,88,48,87",
"words":"姓名网小易"
},
{
"boundingBox":"47,106,264,106,263,134,46,134",
"words":"性别男民族汉"
},
{
"boundingBox":"46,152,328,151,327,177,45,178",
"words":"出199706月01日"
},
{
"boundingBox":"44,195,371,195,371,224,43,224",
"words":"住址北京市海淀区西北旺东路10"
},
{
"boundingBox":"109,224,364,224,363,253,109,253",
"words":"号院中关村软件园西区7号"
},
{
"boundingBox":"47,315,535,316,534,343,46,342",
"words":"公民身份证号码110101199706010022"
}
]
}
draw(json)
                            
查看完整回答
反对 回复 2019-05-12
?
精慕HU

TA贡献1845条经验 获得超8个赞

这种场景建议你试试SVG,跟HTML标签的概念很类似,也可以往里塞图片(image标签)、文字(text标签),只要最外层视口参数写对了就可以自动缩放(而且跟background类似的还有布局定位),也不需要JSON了,直接怼到HTML代码里就成(可以在服务器端渲染或者用模板方案,如果需要js动态搞也有很多js库可以选)。
                            
查看完整回答
反对 回复 2019-05-12
  • 2 回答
  • 0 关注
  • 1261 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号