vue 详细了解canvas(1)--展示图片,鼠标在画布上点哪出现字

一、图片引入这里需要注意一下,不然引入不成功
在这里插入图片描述
二、通过id拿到canvas,通过 getContext(‘2d’)方法获取2D绘制上下文, this.context.drawImage(img,x,y,width,height)方法可以来展示图片, img: 图片 x,y相对于canvas的左上角,其实位置(0,0) wisth:图片的宽 height:图片的高

在这里插入图片描述
三、鼠标按下的位置出现字,首先我们要拿到鼠标坐标的位置e.offsetX, e.offsetY,鼠标自带的参数可以自己去找。
canvas给我们提供了fillText(text,x,y) 方法 text:填写我们想说的话 , x,y同上面一样填写 。 fillStyle修改字体的颜色。font修改字体的大小
在这里插入图片描述

效果图
在这里插入图片描述

<template>
    <div>
        <canvas
            id="canvas"
            ref="canvas"
            width="800"
            height="600"
            @mousedown="canvasDown($event)"
            @mouseup="canvasUp($event)"
            @mousemove="canvasMove($event)"
        ></canvas>
        <img src="../../../assets/img/523.jpg" alt />
    </div>
</template>

<script>
import imgurl from '../../../assets/img/523.jpg'
export default {
  data() {
    return {
      img: new Image(), // 背景图片缓存
      context: {}, // canvas对象
    }
  },
  mounted() {
    this.initDraw()
  },
  methods: {
    initDraw() {
      this.img.src = imgurl
      const canvas = document.querySelector('#canvas')
      this.context = canvas.getContext('2d')

      let w = this.img.width * 600 / this.img.height
      let h = this.img.height * 800 / this.img.width
      console.log(w, h)
      canvas.width = w
      canvas.heigth = h
      setTimeout(() => {
        console.log(this.img.width * 600 / this.img.height)
        this.context.drawImage(this.img, 0, 0, w, h) //在画布上定位图像
      }, 10)
    },
    canvasDown(e) {
      console.log("按下")
      this.context.font = "20px '微软雅黑'";
      this.context.fillStyle = "red"
      this.context.fillText("画布", e.offsetX, e.offsetY)
    },
    canvasMove(e) {
      console.log("移动")
    },
    canvasUp(e) {
      console.log("抬起")
    },
    resetCanvas() { // 清空画布
      this.context.fillStyle = '#fff'
      this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
      this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
      this.context.fillStyle = '#000'
    },

  }
}
</script>

<style>
#canvas {
    border: 1px solid;
}
</style>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值