<template>
<div id="container"></div>
</template>
<script>
export default {
name: 'Container',
data() {
return {
containerDom: null,
cavDom: null,
}
},
mounted() {
this.init()
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
init() {
this.containerDom = document.getElementById('container')
this.cavDom = document.createElement('canvas')
this.cavDom.width = this.containerDom.offsetWidth
this.cavDom.height = this.containerDom.offsetHeight
this.cavDom.id = 'canvasDom'
this.cavDom.style.cursor = 'crosshair'
this.containerDom.appendChild(this.cavDom)
window.addEventListener('resize', this.handleResize)
this.draw()
},
draw() {
const ctx = this.cavDom.getContext('2d')
ctx.strokeStyle = '#2080F7'
ctx.lineWidth = 2
let start = false
let sX = 0
let sY = 0
this.cavDom.onmousedown = ed => {
start = true
sX = ed.offsetX
sY = ed.offsetY
this.cavDom.onmousemove = em => {
if (start) {
ctx.clearRect(0, 0, this.cavDom.width, this.cavDom.height)
ctx.beginPath()
ctx.setLineDash([8, 4])
ctx.rect(sX, sY, em.offsetX - sX, em.offsetY - sY)
ctx.stroke()
}
}
this.cavDom.onmouseup = eu => {
if (start) {
ctx.beginPath()
ctx.setLineDash([])
ctx.rect(sX, sY, eu.offsetX - sX, eu.offsetY - sY)
ctx.stroke()
start = false
console.log(sX, sY, eu.offsetX, eu.offsetY)
}
}
}
},
handleResize() {
this.cavDom.width = this.containerDom.offsetWidth
this.cavDom.height = this.containerDom.offsetHeight
},
},
}
</script>
<style lang="scss">
#container {
width: 100%;
height: 100%;
background-color: antiquewhite;
}
</style>