今天和大家分享一下放大镜的实现,同样也要使用到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
效果图:
感谢阅读