代码块
必须参数:图片地址、框选的位置(左上、右上、右下、左下)。拿到图片后,利用四个点位信息在图片上使用canvas画框并添加对应描述文字,然后将画好的图片地址返回进行回显。
注:需要在显示图片的dom中添加
<canvas ref="imgRef" style="display: none" />
// An highlighted block
/**
* @method drawRect 图片框选方法
* @param that this
*/
const drawRect = (that, imgDetail = {}, rectList = [], lineStyle = {}, textBgWidth = 70, descriptText = '其它') => {
// imgDetail = { // 图片详情(必填)
// imgUrl: '', // 图片地址string(必填)
// imgWidth: 790, // 图片的宽number(非必填)
// imgHeight: 445, // 图片的高number(非必填)
// }
// rectList = [{ // 画框参数,是个数组,因为一张图片可能有多个框框
// objLeft: 50, // 矩形左上角、左下角横坐标number(必填)
// objRight: 560, // 矩形右上角、右下角横坐标number(必填)
// objTop: 300, // 矩形左上角、右上角纵坐标number(必填)
// objBottom: 400, // 矩形左下角、右下角纵坐标number(必填)
// }]
// lineStyle = { // 画框样式(非必填)
// lineWidth: 5, // 线条宽度
// strokeColor: '#46e832' // 线条颜色
// }
// textBgWidth = 70 //描述文字背景框宽度
// descriptText = '其它' // 框的描述文字
if(!imgDetail.imgUrl) {
console.log('图片url不能为空!');
return
}
return new Promise((resolve, reject) => {
try {
loadImg(imgDetail.imgUrl).then((image) => {
const w = imgDetail.imgWidth || image.width // 防止接口中没有返回图片宽高,前端自己取图片本身的宽高
const h = imgDetail.imgHeight || image.height
that.canvas = that.$refs.imgRef
that.canvas.width = w
that.canvas.height = h
// 新建一个canvas对象
that.ctx = that.canvas.getContext('2d')
that.ctx.drawImage(image, 0, 0, w, h) // 在画布上定位图像,并规定图像的宽度和高度
that.ctx.lineWidth = lineStyle.lineWidth || 4
that.ctx.strokeStyle = lineStyle.strokeColor || "#fd0000"
for (let j = 0; j < rectList.length; j++) {
const {
objLeft: x1,
objRight: x2,
objTop: y1,
objBottom: y2
} = rectList[j]
that.ctx.strokeRect(x1, y1, x2 - x1, y2 - y1) // 矩形的位置(x1, y1)宽(x2-x1)高(y2-y1)
// 描述文字背景色、背景框位置
that.ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // 半透明红色背景
that.ctx.fillRect(x1 - 1, y1 - 30, textBgWidth, 30);
// 描述文字颜色、大小、位置,fillText为填充文本,strokeText为描边文本
that.ctx.fillStyle = '#fff';
that.ctx.font="20px Georgia";
that.ctx.fillText(descriptText, x1 + 10, y1 - 10);
}
const imgSrc = that.canvas.toDataURL()
resolve(imgSrc)
}).catch(err => {
console.log('加载图片错误2', err)
reject(err)
})
} catch (err) {
console.log('画框错误', err)
reject(err)
}
})
}
const loadImg = (src) => {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = src
img.setAttribute('crossOrigin', 'anonymous') //跨域处理
img.onload = () => resolve(img)
img.onerror = (err) => {
console.log('加载图片错误1', err)
reject(err)
}
})
}
export default drawRect;