LightCanvas.vue 2.74 KB
<template>
	<div class='lightCanvas'>
		<div class="pic3"><img :src="bgUrl" /></div>
		<canvas id="c3" @click='canvasCLick' width="200" height="200"> <!--宽高写在html里,写在css里有问题-->
			<span>该浏览器不支持canvas内容</span> <!--对于不支持canvas的浏览器显示-->
		 </canvas>
	</div>
</template>

<script>
	export default {
		name: 'LightCanvas',
		data() {
			return{
				bgUrl: '',
				cirAry:[],
				ctx: {}
			}
		},
		methods: {
			imgSize: function (w,h) {
				
			},
			canvasCLick: function (e) {
				if (this.cirAry.length==4) {
					this.$message({
						type:'info',
						message:'最多只能设置四个点'
					})
					return
				}
				var e = e || window.event;
				let currentC = [e.offsetX,e.offsetY];
				let flag = this.isAddCircle(this.cirAry,currentC)
				if (flag===true) {
					this.cirAry.push(currentC)
					this.$parent.lightCancle = true
					if (this.cirAry.length==4) {
						this.$parent.lightNextBtn = true
					}
				}else{
					alert('与其他点重合,请重新选择')
				}
				this.draw()
			},
			draw: function () {
				this.ctx.clearRect(0, 0, 200, 200);
				let that = this;
				this.cirAry.forEach(function (ele,index) {
					that.drawCircle(ele,'yellow')
					if (index>0) {
						that.drawLine(ele,that.cirAry[index-1],'yellow')
					}
					if (index==3) {
						that.drawLine(ele,that.cirAry[0],'yellow')
					}
				})
			},
			drawCircle: function(ary, color, r) {
				var r = r ? r : 2
				this.ctx.beginPath();
				this.ctx.arc(ary[0], ary[1], r, 0, 2 * Math.PI);
				this.ctx.fillStyle = color;
				this.ctx.fill();
			},
			drawLine: function(c1, c2, color, w) {
				var width = w ? w : 2;
				this.ctx.lineWidth = width;
				this.ctx.strokeStyle = color;
				this.ctx.moveTo(c1[0], c1[1]);
				this.ctx.lineTo(c2[0], c2[1]);
				this.ctx.stroke();
			},
			isAddCircle: function(ary, currentC) {
				let flag = true;
				for(let i = 0; i < ary.length; i++) {
					let distance = Math.sqrt(Math.pow(ary[i][0] - currentC[0], 2) + Math.pow(ary[i][1] - currentC[1], 2));
					if(distance < 6) {
						flag = i;
						break;
					}
				}
				return flag
			},
			cancle: function () {
				this.cirAry.pop()
				if (this.cirAry.length==0) {
					this.$parent.lightCancle = false
				}
				this.$parent.lightNextBtn = false
				this.draw()
			}
		},
		mounted() { 
			this.ctx = document.getElementById('c3').getContext('2d');
		}
	}
</script>

<style scoped>
	.lightCanvas{
		position: relative;
		height:230px;
		padding-top: 10px;
	}
	.pic3 {
		position: absolute;
		top: 0;
		left: 0;
		width:200px;
		height:200px;
		left:150px;
		top:10px
	}
	
	.pic3 img {
		margin: 0;
		padding: 0;
		width:200px;
		height:200px
	}
	
	canvas {
		position: absolute;
		margin: 0;
		padding: 0;
		left:150px;
		top:10px
	}
</style>