方案背景

需求

  1. 需要对图片进行标注,导出图片。
  2. 需要标注N多图片最后同时保存。
  3. 需要根据多边形区域数据(区域、颜色、名称)标注。

对应方案

  1. 用canvas实现涂鸦、圆形、矩形的绘制,最终生成图片base64编码用于上传
  2. 大量图片批量上传很耗时间,为了提高用户体验,改为只实现圆形、矩形绘制,最终保存成坐标,下次显示时根据坐标再绘制。
  3. 多边形区域的显示是根据坐标点绘制,名称显示的位置为多边形质心。

代码

<template>
<div>
<canvas
:id="radom"
:class="{canDraw: 'canvas'}"
:width="width"
:height="height"
:style="{'width':`${width}px`,'height':`${height}px`}"
@mousedown="canvasDown($event)"
@mouseup="canvasUp($event)"
@mousemove="canvasMove($event)"
@touchstart="canvasDown($event)"
@touchend="canvasUp($event)"
@touchmove="canvasMove($event)">
</canvas>
</div>
</template>
<script>
// import proxy from './proxy.js'
const uuid = require('node-uuid')
export default {
props: {
canDraw: { // 图片路径
type: Boolean,
default: true
},
url: { // 图片路径
type: String
},
info: { // 位置点信息
type: Array
},
width: { // 绘图区域宽度
type: String
},
height: { // 绘图区域高度
type: String
},
lineColor: { // 画笔颜色
type: String,
default: 'red'
},
lineWidth: { // 画笔宽度
type: Number,
default: 2
},
lineType: { // 画笔类型
type: String,
default: 'circle'
}
},
watch: {
info (val) {
if (val) {
this.initDraw()
}
}
},
data () {
return {
// 同一页面多次渲染时,用于区分元素的id
radom: uuid.v4(),
// canvas对象
context: {},
// 是否处于绘制状态
canvasMoveUse: false,
// 绘制矩形和椭圆时用来保存起始点信息
beginRec: {
x: '',
y: '',
imageData: ''
},
// 储存坐标信息
drawInfo: [],
// 背景图片缓存
img: new Image()
}
},
mounted () {
this.initDraw()
},
methods: {
// 初始化绘制信息
initDraw () {
// 初始化画布
const canvas = document.getElementById(this.radom)
this.context = canvas.getContext('2d')
// 初始化背景图片
this.img.setAttribute('crossOrigin', 'Anonymous')
this.img.src = this.url
this.img.onerror = () => {
var timeStamp = +new Date()
this.img.src = this.url + '?' + timeStamp
}
this.img.onload = () => {
this.clean()
}
// proxy.getBase64({imgUrl: this.url}).then((res) => {
// if (res.code * 1 === 0) {
// this.img.src = 'data:image/jpeg;base64,'+res.data
// this.img.onload = () => {
// this.clean()
// }
// }
// })
// 初始化画笔
this.context.lineWidth = this.lineWidth
this.context.strokeStyle = this.lineColor
},
// 鼠标按下
canvasDown (e) {
if (this.canDraw) {
this.canvasMoveUse = true
// client是基于整个页面的坐标,offset是cavas距离pictureDetail顶部以及左边的距离
const canvasX = e.clientX - e.target.parentNode.offsetLeft
const canvasY = e.clientY - e.target.parentNode.offsetTop
// 记录起始点和起始状态
this.beginRec.x = canvasX
this.beginRec.y = canvasY
this.beginRec.imageData = this.context.getImageData(0, 0, this.width, this.height)
// 存储本次绘制坐标信息
this.drawInfo.push({
x: canvasX / this.width,
y: canvasY / this.height,
type: this.lineType
})
}
},
Area (p0,p1,p2) {
let area = 0.0 ;
area = p0.x * p1.y + p1.x * p2.y + p2.x * p0.y - p1.x * p0.y - p2.x * p1.y - p0.x * p2.y;
return area / 2 ;
},
// 计算多边形质心
getPolygonAreaCenter (points) {
let sum_x = 0;
let sum_y = 0;
let sum_area = 0;
let p1 = points[1];
for (var i = 2; i < points.length; i++) {
let p2 = points[i];
let area = this.Area(points[0],p1,p2) ;
sum_area += area ;
sum_x += (points[0].x + p1.x + p2.x) * area;
sum_y += (points[0].y + p1.y + p2.y) * area;
p1 = p2 ;
}
return {
x: sum_x / sum_area / 3,
y: sum_y / sum_area / 3
}
},
// 根据坐标信息绘制图形
drawWithInfo () {
this.info.forEach(item => {
this.context.beginPath()
if (!item.type) {
// 设置颜色
this.context.strokeStyle = item.regionColor
this.context.fillStyle = item.regionColor
// 绘制多边形的边
if (typeof item.region === 'string') {
item.region = JSON.parse(item.region)
}
item.region.forEach(point => {
this.context.lineTo(point.x * this.width, point.y * this.height)
})
this.context.closePath()
// 在多边形质心标注文字
let point = this.getPolygonAreaCenter(item.region)
this.context.fillText(item.areaName, point.x * this.width, point.y * this.height)
} else if (item.type === 'rec') {
this.context.rect(item.x * this.width, item.y * this.height, item.w * this.width, item.h * this.height)
} else if (item.type === 'circle') {
this.drawEllipse(this.context, (item.x + item.a) * this.width, (item.y + item.b) * this.height, item.a > 0 ? item.a * this.width : -item.a * this.width, item.b > 0 ? item.b * this.height : -item.b * this.height)
}
this.context.stroke()
})
},
// 鼠标移动时绘制
canvasMove (e) {
if (this.canvasMoveUse && this.canDraw) {
// client是基于整个页面的坐标,offset是cavas距离pictureDetail顶部以及左边的距离
let canvasX = e.clientX - e.target.parentNode.offsetLeft
let canvasY = e.clientY - e.target.parentNode.offsetTop
if (this.lineType === 'rec') { // 绘制矩形时恢复起始点状态再重新绘制
this.context.putImageData(this.beginRec.imageData, 0, 0)
this.context.beginPath()
this.context.rect(this.beginRec.x, this.beginRec.y, canvasX - this.beginRec.x, canvasY - this.beginRec.y)
let info = this.drawInfo[this.drawInfo.length - 1]
info.w = canvasX / this.width - info.x
info.h = canvasY / this.height - info.y
} else if (this.lineType === 'circle') { // 绘制椭圆时恢复起始点状态再重新绘制
this.context.putImageData(this.beginRec.imageData, 0, 0)
this.context.beginPath()
let a = (canvasX - this.beginRec.x) / 2
let b = (canvasY - this.beginRec.y) / 2
this.drawEllipse(this.context, this.beginRec.x + a, this.beginRec.y + b, a > 0 ? a : -a, b > 0 ? b : -b)
let info = this.drawInfo[this.drawInfo.length - 1]
info.a = a / this.width
info.b = b / this.height
}
this.context.stroke()
}
},
// 绘制椭圆
drawEllipse (context, x, y, a, b) {
context.save()
var r = (a > b) ? a : b
var ratioX = a / r
var ratioY = b / r
context.scale(ratioX, ratioY)
context.beginPath()
context.arc(x / ratioX, y / ratioY, r, 0, 2 * Math.PI, false)
context.closePath()
context.restore()
},
// 鼠标抬起
canvasUp (e) {
if (this.canDraw) {
this.canvasMoveUse = false
}
},
// 获取坐标信息
getInfo () {
return this.drawInfo
},
// 清空画布
clean () {
this.context.drawImage(this.img, 0, 0, this.width, this.height)
this.drawInfo = []
if (this.info && this.info.length !== 0) this.drawWithInfo()
}
}
}
</script>
<style lang="scss" scoped>
.canvas{
cursor: crosshair;
}
</style>

必须传入的参数

  • 图片路径
url: string
  • 绘图区域宽度
width: string
  • 绘图区域高度
height: string

选择传入的参数

  • 是否可以绘制,默认true
canDraw: boolean
  • 坐标点信息,不传入则不绘制
info: string
  • 是否可绘制,默认true
canDraw: boolean
  • 绘图颜色,默认red
lineColor: string
  • 绘图笔宽度,默认2
lineWidth: number
  • 绘图笔类型,rec、circle,默认rec
lineType: string

可以调用的方法

  • 清空画布
clean()
  • 返回坐标点信息
getInfo()

特殊说明

  • canvas对象不能获得坐标,是通过父元素坐标获取的,所以该组件的父元素以上的层级不能有太多的定位、嵌套,否则绘制坐标会偏移。
  • 域名不同的图片可能存在跨域问题,看过很多资料没有太好的办法,最后项目中是用node服务做了一个图片转为base64的接口,再给canvas绘制解决的。并不一定适用于其他项目,如果有更好的办法解决欢迎分享。
  • 导出坐标点数据只能导出规则图案的坐标点,因为随意涂鸦的坐标点太多时会崩溃的(虽然没试过具体到什么程度会崩溃),如果有高性能的实现方式欢迎分享。
  • 如果涂鸦后保存再请求图片url出现请求不到的情况,是因为CDN缓存的问题,在图片路径后面拼个随机码就可以解决。

原文地址:https://segmentfault.com/a/1190000016852958

vue组件:canvas实现图片涂鸦功能的更多相关文章

  1. vue项目js实现图片放大镜功能

    效果图:   我写的是vue的组件形式,方便复用,图片的宽高,缩放的比例可以自己定义 magnifier.vue <template> <div class="magnif ...

  2. vue组件利用formdata图片预览以及上传《转载》

    转载修改 在项目中直接新建一个单文件页,复制一下代码即可       upload组件: <template> <div class="vue-uploader" ...

  3. vue组件利用formdata图片预览以及上传

    转载修改 在项目中直接新建一个单文件页,复制一下代码即可       upload组件: <template> <div class="vue-uploader" ...

  4. vue 实现点击图片放大

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.建立子组件,来实现图片方法功能: BigImg.vue <template> <!-- 过渡 ...

  5. vue组件如何被其他项目引用

    自己写的vue组件怎么才能让其他人引用呢,或者是共用组件如何让其他项目引用.本文就粗细的介绍下,如有疑问欢迎共同讨论.在这里你能了解下如下知识点: 1. 如何发布一个包到npmjs仓库上 2.如何引用 ...

  6. Laravel 项目中编写第一个 Vue 组件

    和 CSS 框架一样,Laravel 不强制你使用什么 JavaScript 客户端框架,但是开箱对 Vue.js 提供了良好的支持,如果你更熟悉 React 的话,也可以将默认的脚手架代码替换成 R ...

  7. vue中图片放大镜功能

    仿淘宝详情页图片鼠标移过去可对图片放大显示在右侧 效果图如下图,此功能支持PC端与移动端 接下来进入代码实现环节: 先准备两张图片,一张小图片叫 '土味.jpg',大小160*91:一张大图片叫 ' ...

  8. 通过base64实现图片下载功能(基于vue)

    1. 使用场景 当我们处理图片下载功能的时候,如果本地的图片,那么是可以通过canvas获得图片的base64的,方法如下.但是如果图片的url存在跨域问题的话,下面的方法将行不通,这时候我们可以另辟 ...

  9. 从web编辑器 UEditor 中单独提取图片上传,包含多图片单图片上传以及在线涂鸦功能

    UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码.(抄的...) UEditor是非常好用的富文 ...

随机推荐

  1. HDU-2119-Matrix(最大匹配)

    链接:https://vjudge.net/problem/HDU-2119#author=Smilencer 题意: 众所周知,tyz是一个写bug小能手,以至于如果没有队友的帮助,就ac不了程序. ...

  2. Atcoder AGC016 E Poor Turkeys

    比赛的时候口胡这道题口胡了一年,看完题解被教做人 题意:有n只火鸡,m个猎人按序来杀火鸡,从自己预先选的两只中杀一只,问有多少火鸡对可以同时存活 考虑对于每一只火鸡i,按时间逆序维护一个最小的集合Si ...

  3. Java通过图片url地址获取图片base64位字符串的两种方式

    工作中遇到通过图片的url获取图片base64位的需求.一开始是用网上的方法,通过工具类Toolkit,虽然实现的代码比较简短,不过偶尔会遇到图片转成base64位不正确的情况,至今不知道为啥. 之后 ...

  4. org.apache.ibatis.binding.BindingException【原因汇总】

    这个问题整整纠结了我四个多小时,心好累啊...不废话... 背景:Spring整合Mybatis 报错:org.apache.ibatis.binding.BindingException: Inva ...

  5. PostgreSQL 导出导入表中指定查询数据

    创建一临时表: create table test_view as select * from test where date(to_timestamp(endtime))>='2012-09- ...

  6. (转)AIX 中 Paging Space 使用率过高的分析与解决

    AIX 中 Paging Space 使用率过高的分析与解决 原文:https://www.ibm.com/developerworks/cn/aix/library/au-cn-pagingspac ...

  7. SQL server下所有表名及字段名及注释查询

    --查询所有表及注释SELECTA.name ,C.valueFROM sys.tables A LEFT JOIN sys.extended_properties C ON C.major_id = ...

  8. cas实现单点登录原理

    1.基于Cookie的单点登录的回顾        基于Cookie的单点登录核心原理: 将用户名密码加密之后存于Cookie中,之后访问网站时在过滤器(filter)中校验用户权限,如果没有权限则从 ...

  9. 洛谷 P2983 [USACO10FEB]购买巧克力Chocolate Buying

    购买巧克力Chocolate Buying 乍一看以为是背包,然后交了一个感觉没错的背包上去. #include <iostream> #include <cstdio> #i ...

  10. 洛谷 P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here

    你的飞碟在这儿 难度:☆ Code: #include<iostream> #include<cstring> #include<cstdio> using nam ...