npm install hammerjs
在main.js文件中
import Hammer from 'hammerjs'
html
<img
v-bind:src="`/static/choicePic/${itemCode}.jpg`"
alt=""
id="amplification"
/>
js在页面中vue生命周期的 update钩子
let amplification = document.querySelector("#amplification");
console.log("amplification", amplification);
let hammertime = new Hammer(amplification);
hammertime.get("pinch").set({ enable: true });
let posX = 0,
posY = 0,
scale = 1,
last_scale = 1,
last_posX = 0,
last_posY = 0,
max_pos_x = 0,
max_pos_y = 0,
transform = "";
const el = amplification;
hammertime.on(
"panleft panright panup pandown tap press pdoubletap pan pinch panend pinchend",
function (ev) {
if (ev.type === "doubletap") {
transform = "translate3d(0, 0, 0) " + "scale3d(2, 2, 1) ";
scale = 2;
last_scale = 2;
try {
if (
window
.getComputedStyle(el, null)
.getPropertyValue("-webkit-transform")
.toString() !== "matrix(1, 0, 0, 1, 0, 0)"
) {
transform = "translate3d(0, 0, 0) " + "scale3d(1, 1, 1) ";
scale = 1;
last_scale = 1;
}
} catch (err) {}
// tslint:disable-next-line: deprecation
el.style.webkitTransform = transform;
transform = "";
}
// pan
if (scale !== 1) {
posX = last_posX + ev.deltaX;
posY = last_posY + ev.deltaY;
max_pos_x = Math.ceil(((scale - 1) * el.clientWidth) / 2);
max_pos_y = Math.ceil(((scale - 1) * el.clientHeight) / 2);
if (posX > max_pos_x) {
posX = max_pos_x;
}
if (posX < -max_pos_x) {
posX = -max_pos_x;
}
if (posY > max_pos_y) {
posY = max_pos_y;
}
if (posY < -max_pos_y) {
posY = -max_pos_y;
}
}
// pinch
if (ev.type === "pinch") {
scale = Math.max(0.999, Math.min(last_scale * ev.scale, 4));
}
if (ev.type === "pinchend") {
last_scale = scale;
}
// panend
if (ev.type === "panend") {
last_posX = posX < max_pos_x ? posX : max_pos_x;
last_posY = posY < max_pos_y ? posY : max_pos_y;
}
if (scale !== 1) {
transform =
"translate3d(" +
posX +
"px," +
posY +
"px, 0) " +
"scale3d(" +
scale +
", " +
scale +
", 1)";
}
if (transform) {
// tslint:disable-next-line: deprecation
el.style.webkitTransform = transform;
}
}
);
效果看红旗手机端官网高定H9+
参考文章 https://cloud.tencent/developer/article/1454902?from=information.detail.hammer.js%20%E6%94%BE%E5%A4%A7%E7%BC%A9%E5%B0%8F
文档:https://www.jianshu/p/0b0b9364f967
更多推荐
黄小鸭暴走记之 vue项目移动端图片放大功能 hammer包的引入和使用
发布评论