前端放大镜功能实现

今天和大家分享一下放大镜的实现,同样也要使用到canvas,不了解的同学可以先去学习一下

这个功能相比前一篇的图片裁剪还是比较简单的,至少我这里的代码量只有三分之一,同样也要使用到drawImage这个方法,不熟悉的同学可以先去看一下上一篇介绍图片裁剪的,里面有说明https://blog.csdn.net/exxes/article/details/128733586?spm=1001.2014.3001.5502

先说思路,和裁剪的差不多,都是监听鼠标的坐标,放大效果无非就是裁剪出一个较小的区域然后给他一个正常的宽高,比如你的放大镜宽高都是100,要放大2倍,那么放大的区域就是以鼠标坐标为中心宽高是50的区域,把他放到100的框里面

下面直接贴代码

<div class="enlarge-content" @mousemove.stop="moveMirror" 
     :style="{ marginBottom : height / 2 + 'px' }">
            <img class="origin-img" ref="windLargeImg" :src="imgSrc"
                :style="{ width: imgWidth + 'px', height: imgHeight + 'px' }" />

            <div class="enlarge-mirror" @click="startUse"
                :style="{ width: width + 'px', height: height + 'px', 
                        top: mirrorY - height / 2 + 'px', left: mirrorX - width / 2 + 'px' }">
                <canvas id="wind-enlarge-canvas" :width="width * ratio" 
                        :height="height * ratio"
                        :style="{ width: width + 'px', height: height + 'px' }" />
            </div>
        </div>

function moveMirror(e: any) {
    if (isUse.value) {
        let nx = e.x - contentX
        let ny = e.y - contentY
        if (nx < 0 || ny < 0 || nx > props.imgWidth || ny > props.imgHeight) {
            return
        }
        mirrorX.value = nx
        mirrorY.value = ny
        ctx?.clearRect(0, 0, props.width * ratio.value, props.height * ratio.value)
        ctx?.drawImage(img, (nx - props.width / 2 / props.enlargeScale) / scale, 
                            (ny - props.height / 2 / props.enlargeScale) / scale, 
                            props.width / props.enlargeScale / scale, 
                            props.height / props.enlargeScale / scale, 
                            0, 0, props.width * ratio.value, props.height * ratio.value)
    }
}

由于放大镜是以鼠标坐标为中心,所以absolute定位中需要中心坐标减去一半的宽高,由于是相对于原图裁剪所以要除以比例scale

效果图:

感谢阅读

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值