vue如何实现在页面上画画_vue组件:canvas实现图片涂鸦功能

方案背景

需求

需要对图片进行标注,导出图片。

需要标注N多图片最后同时保存。

需要根据多边形区域数据(区域、颜色、名称)标注。

对应方案

用canvas实现涂鸦、圆形、矩形的绘制,最终生成图片base64编码用于上传

大量图片批量上传很耗时间,为了提高用户体验,改为只实现圆形、矩形绘制,最终保存成坐标,下次显示时根据坐标再绘制。

多边形区域的显示是根据坐标点绘制,名称显示的位置为多边形质心。

代码

: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)">

// 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 {

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中可以使用 HTML5 的 Canvas API 来实现页面画画,可以通过在 Vue 组件中添加 canvas 元素,并在 mounted 钩子函数中获取其 2D 上下文来实现。 以下是一个实现页面画画的示例代码: ```html <template> <div> <canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"></canvas> </div> </template> <script> export default { name: 'DrawCanvas', data() { return { isDrawing: false, lastX: 0, lastY: 0, ctx: null, } }, mounted() { this.ctx = this.$refs.canvas.getContext('2d'); }, methods: { startDrawing(e) { this.isDrawing = true; this.lastX = e.offsetX; this.lastY = e.offsetY; }, draw(e) { if (!this.isDrawing) return; this.ctx.beginPath(); this.ctx.moveTo(this.lastX, this.lastY); this.ctx.lineTo(e.offsetX, e.offsetY); this.ctx.stroke(); this.lastX = e.offsetX; this.lastY = e.offsetY; }, stopDrawing() { this.isDrawing = false; }, }, } </script> <style scoped> canvas { width: 100%; height: 100%; border: 1px solid #000; } </style> ``` 上面的代码中,我们在组件中添加了一个 canvas 元素,并为其添加了三个事件监听器,分别是 @mousedown、@mousemove 和 @mouseup,用于开始、绘制和停止绘制画画。 在 mounted 钩子函数中,我们获取了 canvas 元素的 2D 上下文,并将其保存在组件的 this.ctx 属性中。 在组件的 methods 中,我们定义了三个方法,分别是 startDrawing、draw 和 stopDrawing。 startDrawing 方法用于在鼠标按下时记录当前鼠标的位置,并将 isDrawing 属性设置为 true。 draw 方法用于在鼠标移动时绘制线条,如果 isDrawing 为 true,则使用 moveTo 和 lineTo 方法绘制一条线段,并将 lastX 和 lastY 属性更新为当前鼠标的位置。 stopDrawing 方法用于在鼠标松开时将 isDrawing 属性设置为 false,停止绘制画画。 最后,我们在组件的 template 中使用 ref 属性来获取 canvas 元素,并为其添加样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值