<template>
<div style="display: flex;justify-content: center;margin: 20px">
<canvas
id="myCanvas"
style="border:1px solid #d3d3d3;"
@mousedown="handleMousedown"
@mouseup="handleMouseup"
/>
</div>
</template>
<script>
export default {
name: 'Home',
components: {},
data() {
return {
down: ''
}
},
mounted() {
var canvas = document.getElementById('myCanvas')
var ctx = canvas.getContext('2d')
var img = new Image()
ctx.width = 400
ctx.height = 400
img.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.huachenyuanyang.com%2Fuploads%2Fallimg%2F160506%2F1-160506102043158.jpg&refer=http%3A%2F%2Fwww.huachenyuanyang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674111147&t=a8c60e306bf49d32038208dc8630864f' // 图片地址示例
img.onload = function() {
document.getElementById('myCanvas').width = img.width
document.getElementById('myCanvas').height = img.height
ctx.drawImage(img, 0, 0, img.width, img.height)
}
},
methods: {
handleMousedown(e) {
if (e.button === 0) {
this.down = e
}
},
handleMouseup(e) {
if (e.button === 0) {
// console.log('松开', e)
var c = document.getElementById('myCanvas')
var ctx = c.getContext('2d')
ctx.strokeStyle = '#EB3324'
// 绘制矩形
var { offsetX, offsetY } = this.down
var width = offsetX - e.offsetX
var height = offsetY - e.offsetY
if (width < 0) {
width *= -1
}
if (height < 0) {
height *= -1
}
ctx.strokeRect(offsetX > e.offsetX ? e.offsetX : offsetX, offsetY > e.offsetY ? e.offsetY : offsetY, width, height)
}
}
}
}
</script>
<style scoped>
</style>
vue实现图片标注
最新推荐文章于 2024-06-18 15:23:28 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)