学习Vue3系列-开发滑动图片组件

前言

最近有个项目是需要用到,滑动图片组件来进行用户登录验证,本着拿来精神,上去github找到了一款比较适合项目开发的插件。

  1. vue-slider-vertify

但是本着学习精神,所以决定深入研究源码,模仿一下优秀的代码思路,提高一下自己的水平

3440b7a216a7b2f8518149e9452a3799.jpg

技术选型

  1. Vue3
  2. Canvas

确定组件基础参数

在写组件的过程,其实我们都是要思考,如何能够让业务方使用起来最为方便,我们就先假定以下使用方式

typescript复制代码<vertify :height="80" :width="300" />
<script setup lang="ts">
import vertify from "@/components/Vertify/index.vue"
<script>

在components/Vertify新建index.vue,该组件编写还是使用传统的SFC的形式

确定HTML布局

image.png

如何确保canvas能绘制图片

用canvas绘制图片的时候,需要确保图片加载完成后,在进行绘制,否则会出现图片加载不出来的情况。 为了解决这个问题,我们可以使用 JavaScript 来确保图片加载完成后再进行绘制。一种常用的方法是使用图像的 onload 事件,在图像加载完成时触发相应的回调函数,进行绘制操作。

js复制代码<script setup lang="ts">
import { ref, onMounted } from "vue"
export interface IProps {
  width?: number
  height?: number
}
const props = withDefaults(defineProps<IProps>(), {
  width: 320,
  height: 160
})
//目标图片
const canvasRef = ref<HTMLCanvasElement | null>(null)
// 缺失的图片
const blockRef = ref<HTMLCanvasElement | null>(null)

const initImg = () => {
  const img = createImg(() => {
    draw(img)
  })
}
function getRandomNumberByRange(start: number, end: number) {
  return Math.round(Math.random() * (end - start) + start)
}
const getRandomImgSrc = () => {
  return `https://picsum.photos/id/${getRandomNumberByRange(0, 1084)}/${props.width}/${props.height}`
}
const createImg = (onload: VoidFunction) => {
  const img = new Image()
  img.crossOrigin = "Anonymous"
  img.onload = onload
  img.onerror = () => {
    ;(img as any).setSrc(getRandomImgSrc()) // 图片加载失败的时候重新加载其他图片
  }
  ;(img as any).setSrc = (src: string) => {
    const isIE = window.navigator.userAgent.indexOf("Trident") > -1
    if (isIE) {
      // IE浏览器无法通过img.crossOrigin跨域,使用ajax获取图片blob然后转为dataURL显示
      const xhr = new XMLHttpRequest()
      xhr.onloadend = function (e: any) {
        const file = new FileReader() // FileReader仅支持IE10+
        file.readAsDataURL(e.target.response)
        file.onloadend = function (e) {
          img.src = e?.target?.result as string
        }
      }
      xhr.open("GET", src)
      xhr.responseType = "blob"
      xhr.send()
    } else img.src = src
  }
  ;(img as any).setSrc(getRandomImgSrc())
  return img
}

const draw = (img: HTMLImageElement) => {
  if (canvasRef.value && blockRef.value) {
    const canvasCtx = canvasRef.value.getContext("2d") as CanvasRenderingContext2D
    const blockCtx = blockRef.value.getContext("2d") as CanvasRenderingContext2D
    // const img = createImg()
    canvasCtx.drawImage(img, 0, 0, props.width, props.height)
  }
}

onMounted(() => {
  initImg()
})
</script>

image.png

  • 这个时候出现两张一模一样的图片,我们还需要通过canvas中的fill和clip方法对图片进行填充和裁剪。

如何形成两个切片区域

js复制代码export interface IProps {
  width?: number
  height?: number
  l?: number
  r?: number
}
const props = withDefaults(defineProps<IProps>(), {
  width: 320,
  height: 160,
  l: 42,
  r: 9
})
const drawPath = (ctx: any, x: number, y: number, operation: "fill" | "clip") => {
  ctx.beginPath()
  ctx.moveTo(x, y)
  ctx.arc(x + props.l / 2, y - props.r + 2, props.r, 0.72 * PI, 2.26 * PI)
  ctx.lineTo(x + props.l, y)
  ctx.arc(x + props.l + props.r - 2, y + props.l / 2, props.r, 1.21 * PI, 2.78 * PI)
  ctx.lineTo(x + props.l, y + props.l)
  ctx.lineTo(x, y + props.l)
  ctx.arc(x + props.r - 2, y + props.l / 2, props.r + 0.4, 2.76 * PI, 1.24 * PI, true)
  ctx.lineTo(x, y)
  ctx.lineWidth = 2
  ctx.fillStyle = "rgba(255, 255, 255, 0.7)"
  ctx.strokeStyle = "rgba(255, 255, 255, 0.7)"
  ctx.stroke()
  ctx.globalCompositeOperation = "destination-over"
  operation === "fill" ? ctx.fill() : ctx.clip()
}
const draw = (img: HTMLImageElement) => {
  if (canvasRef.value && blockRef.value) {
    const canvasCtx = canvasRef.value.getContext("2d") as CanvasRenderingContext2D
    const blockCtx = blockRef.value.getContext("2d") as CanvasRenderingContext2D
    // 随机位置创建拼图位置
    xRef.value = getRandomNumberByRange(L + 10, props.width - (L + 10))
    yRef.value = getRandomNumberByRange(10 + props.r * 2, props.height - (L + 10))
    drawPath(canvasCtx, xRef.value, yRef.value, "fill")
    drawPath(blockCtx, xRef.value, yRef.value, "clip")
    canvasCtx.drawImage(img, 0, 0, props.width, props.height)
    blockCtx.drawImage(img, 0, 0, props.width, props.height)
  }
}

ctx.globalCompositeOperation = "destination-over" 这段代码在 Canvas 上下文中设置全局合成操作模式(globalCompositeOperation)。指定 destination-over 作为全局合成操作模式,它定义了绘制的新图形如何与已有的图形叠加。

具体来说,destination-over 操作模式会将新绘制的图形置于已有图形的下方。换句话说,新图形在绘制时会位于已有图形的背后。这意味着通过使用这种操作模式,你可以先绘制已有图形,然后再将新的图形绘制在已有图形的下方,从而创建种遮罩或者层叠效果。

在这段代码中,ctx.globalCompositeOperation = "destination-over" 的目的可能是为了确保后续的绘制操作(ctx.fill() 或 ctx.clip())以当前绘制的图形从背后显示。 此时的效果如下:

image.png

移动底部底部切片

js复制代码const draw = (img: HTMLImageElement) => {
  if (canvasRef.value && blockRef.value) {
    ...
    // 提取滑块并放到最左边
    const y1 = yRef.value - props.r * 2 - 1
    // x,y,width,height
    const ImageData = blockCtx.getImageData(xRef.value - 3, y1, L, L)
    blockRef.value.width = L
    blockCtx.putImageData(ImageData, 0, y1)
  }
}
  • 通过调用 getRandomNumberByRange() 函数,在指定范围内生成随机的 x 和 y 坐标,用于确定拼图的位置。
  • 调用 drawPath() 函数在原始图片 Canvas 和滑块 Canvas 上绘制路径,分别使用 "fill" 和 "clip" 类型填充路径,从而创建拼图的视觉效果。
  • 使用 Image() 方法在原始图片 Canvas 和滑块 Canvas 上绘制图片。将加载完成的图片绘制到 Canvas 上下文中。
  • 使用 getImageData() 方法从滑块 Canvas 中提取滑块的图像数据。其中,提取区域的起始点的 x 坐标为 xRef.value - 3,y 坐标为 y1,宽度和高度都是 L。
  • 使用 `putImageData 方法将提取的图像数据放回滑块 Canvas,并绘制在左侧位置,即将滑块放置到最左边。

其中const y1 = yRef.value - props.r * 2 - 1是用来计算 滑块顶部的 y 坐标 (yRef.value) 减去滑块高度 (props.r * 2) 再减移量 (- 1),可以得到滑块提取区域的起始点的 y 坐标 y1。这个值用于确定从滑块 Canvas 中提取图像数据的矩形区域的位置。

此时在通过绝对定位,把底部图片切片防止canvasRef中去。

css复制代码.block {
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  cursor: grab;
}

image.png

如何实现拖拽

复制代码    class="vertifyWrap"
    :style="{
      width: props.width + 'px',
      margin: '0 auto'
    }"
    @mouseup="handleDragEnd"
    @mousemove="handleDragMove"
  >
    <div class="canvasArea">
      <canvas :width="width" :height="height" ref="canvasRef" />
      <canvas ref="blockRef" :width="width" :height="height" class="block" @mousedown="handleDragStart" />
    </div>
  </div>
  const handleDragStart = (e: MouseEvent) => {
  originXRef.value = e.clientX
  originYRef.value = e.clientY
  isMouseDownRef.value = true
}
const handleDragMove = (e: MouseEvent) => {
  if (!isMouseDownRef.value) return false
  e.preventDefault()
  const eventX = e.clientX
  const moveX = eventX - originXRef.value
  if (moveX < 0 || moveX + 40 + 20 >= props.width) return false
  const blockLeft = moveX
  if (blockRef.value) {
    blockRef.value.style.left = blockLeft + "px"
  }
}
const handleDragEnd = (e: MouseEvent) => {
  if (!isMouseDownRef.value) return false
  isMouseDownRef.value = false
  const eventX = e.clientX
  if (eventX === originXRef.value) return false
}

把mousemove绑定在vertifyWrap的目的是为了拖拽的过程中,过快防止指针丢失,无法拖动的问题。在handleDragMove()函数中计算拖动的边界值即可。

底部slider拖动

js复制代码    <div
      :class="sliderClass"
      :style="{
        width: width + 'px'
      }"
    >
      <div class="sliderMask" :style="{ width: sliderLeft + 'px' }">
        <div class="slider" :style="{ left: sliderLeft + 'px' }" @mousedown="handleDragStart">
          <div className="sliderIcon">&rarr;</div>
        </div>
      </div>
    </div>
 const handleDragMove = (e: MouseEvent) => {
      if (!isMouseDownRef.value) return false
      e.preventDefault()
      const eventX = e.clientX
      const moveX = eventX - originXRef.value
      if (moveX < 0 || moveX + 40 + 20 >= props.width) return false
      sliderLeft.value = moveX
      const blockLeft = moveX
      if (blockRef.value) {
        blockRef.value.style.left = blockLeft + "px"
      }
}

在sliderMask中绑定上sliderLeft变量用来控制底部的slider的left偏移值,但是在拖动的过程中,会发现以下问题

1691333366240.png

发现了底部方块与上面出现不对齐的情况,这是由于可视区域目前都是props.width。所以sliderLeft和blockLeft不能是同一个值。

js复制代码const handleDragMove = (e: MouseEvent) => {
  if (!isMouseDownRef.value) return false
  e.preventDefault()
  const eventX = e.clientX
  const moveX = eventX - originXRef.value
  if (moveX < 0 || moveX + 40 >= props.width) return false
  sliderLeft.value = moveX
  const blockLeft = ((props.width - 40 - 20) / (props.width - 40)) * moveX
  if (blockRef.value) {
    blockRef.value.style.left = blockLeft + "px"
  }
}

添加刷新功能

js复制代码const handleRefresh = () => {
  reset()
}
const reset = () => {
  if (canvasRef.value && blockRef.value) {
    const canvasCtx = canvasRef.value.getContext("2d") as CanvasRenderingContext2D
    const blockCtx = blockRef.value.getContext("2d") as CanvasRenderingContext2D
    // 重置样式
    sliderLeft.value = 0
    sliderClass.value = "sliderContainer"
    blockRef.value.width = props.width
    blockRef.value.style.left = 0 + "px"

    // 清空画布
    canvasCtx.clearRect(0, 0, props.width, props.height)
    blockCtx.clearRect(0, 0, props.width, props.height)

    // 重新加载图片
    console.log(getRandomImgSrc(), "getRandomImgSrc()")
    imgRef.value.setSrc(getRandomImgSrc())
  }
}

至此,滑动组件的核心代码就已经完成了,在这个过程学习到了ctx.fill() 和ctx.clip()的使用方法,也知道了在canvas中绘制图片的技巧,还是相对有收获的。

猜你喜欢

转载自blog.csdn.net/Cipher_Y/article/details/132147302