vue2.0和canvas进行编码,写出按住Ctrl键和鼠标左键,进行拖拽,生成圆形图案的功能

<template>
  <div>
    <canvas ref="canvas" @mousedown="onMouseDown" @mouseup="onMouseUp" @mousemove="onMouseMove"></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      canvas: null,
      ctx: null,
      isDragging: false,
      ctrlKey: false,
      startX: 0,
      startY: 0,
      endX: 0,
      endY: 0,
      radius: 20,
    };
  },
  mounted() {
    this.canvas = this.$refs.canvas;
    this.ctx = this.canvas.getContext('2d');
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.ctx.fillStyle = 'rgba(255,255,255,0.8)';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
  },
  methods: {
    // 按下鼠标左键事件
    onMouseDown(event) {
      this.startX = event.clientX;
      this.startY = event.clientY;
      this.isDragging = true;
      // 判断是否按住Ctrl键
      this.ctrlKey = event.ctrlKey;
    },
    // 松开鼠标左键事件
    onMouseUp(event) {
      this.endX = event.clientX;
      this.endY = event.clientY;
      if (this.isDragging) {
        // 如果按住Ctrl键,则绘制圆形
        if (this.ctrlKey) {
          this.drawCircle();
        }
      }
      this.isDragging = false;
    },
    // 移动鼠标事件
    onMouseMove(event) {
      if (this.isDragging) {
        // 如果按住Ctrl键,则绘制临时圆形
        if (this.ctrlKey) {
          this.drawTempCircle(event.clientX, event.clientY);
        }
      }
    },
    // 绘制圆形
    drawCircle() {
      const x = (this.startX + this.endX) / 2;
      const y = (this.startY + this.endY) / 2;
      this.ctx.beginPath();
      this.ctx.arc(x, y, this.radius, 0, 2 * Math.PI);
      this.ctx.fillStyle = '#ff0000';
      this.ctx.fill();
    },
    // 绘制临时圆形
    drawTempCircle(x, y) {
      this.ctx.fillStyle = 'rgba(255,255,255,0.8)';
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      this.ctx.beginPath();
      this.ctx.arc(x, y, this.radius, 0, 2 * Math.PI);
      this.ctx.fillStyle = '#ff0000';
      this.ctx.fill();
    },
  },
};
</script>

该示例代码使用Vue的单文件组件格式,包含一个canvas元素和对应的事件监听器和方法。在鼠标事件中,通过判断是否按住Ctrl键来绘制圆形或临时圆形,绘制时使用canvas的API来进行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值