Ambiente:
cat package.json
...
"dependencies": {
"core-js": "^2.6.5",
"vue": "^2.6.10",
"vant": "^2.12.3"
},
....
A demonstração só precisa de canvas, van-uploader, van-button para ser concluída
<template>
<div class="roc">
<canvas id="mycanvas" width="0" height="0" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<van-uploader :before-read="beforeRead" :after-read="afterRead"/>
<div>使用时间: {
{
speed}}</div>
<van-button type="primary" @click="doSubmit">提交</van-button>
</div>
</template>
Depois de carregar a imagem, renderize a imagem na tela
afterRead(file) {
console.log(file);
this.fileList[0] = file
this.doDraw(file.content,null)
},
doDraw(file_content){
var canvas = document.getElementById("mycanvas")
var context = canvas.getContext('2d')
var img = new Image()
img.src = file_content
img.onload = function(){
if(img.complete){
// 根据图像重新设定了canvas的长宽
canvas.setAttribute("width",img.width)
canvas.setAttribute("height",img.height)
// 绘制图片
context.drawImage(img,0,0,img.width,img.height)
}
}
},
Use van-uploade para fazer upload de fotos para a interface de reconhecimento de imagem e obter os resultados do reconhecimento
doSubmit() {
var file = this.fileList[0]
let that = this
console.log(file);
const form = new FormData()
form.append('file', file.file)
form.append('compress', 960)
fetch('/api-ocr/api/tr-run/', {
// 可以改为任意ocr接口
method: 'POST',
body: form,
}).then((data) => {
that.speed = data.speed_time // 识别速度
that.drawTextLayar(data.raw_out) //识别后的图片和内容
})
},
Comece a renderizar a camada TextLayar
Crie um div com o mesmo tamanho da imagem carregada,
escreva cada resultado de reconhecimento em um sub-div e, em seguida, grave-o no div total
drawTextLayar(dataList){
// 0: (4) [[43, 60], [663, 60], Array(2), Array(2)]
// 1: "1、 通过宝贝核心关键词一键查询类目归属"
// 2: 0.7945398092269897
// 创建一个TextLayer层的div
var div = this.createContainer()
dataList.forEach(e1 => {
this.addLayar(e1[1],e1[0][0],div)
});
},
createContainer(){
var canvas = document.getElementById("mycanvas")
var rect = canvas.getBoundingClientRect();
// Create a Div
var div = document.createElement("div");
div.style.position = "absolute";
div.style.zIndex = "100";
div.style.width = rect.width+"px";
div.style.height = rect.height+"px";
document.body.appendChild(div);
return div;
},
addLayar(text,position,container){
const _text = text.split('、 ')[1] //简单处理下文字
var textLayer = document.createElement("div");
textLayer.innerHTML = _text;
textLayer.style.position = "absolute";
textLayer.style.top = (position[1]+5)+"px";
textLayer.style.left = (position[0]+5)+"px";
textLayer.style.zIndex = "100";
textLayer.style.color = "black";
textLayer.style.fontSize = "20px";
textLayer.style.userSelect = "text";
container.appendChild(textLayer);
}
Desta forma, há uma camada de texto na camada superior da imagem exibida e o texto pode ser copiado