项目里用到canvas,需要做到canvas的手指拖动效果,现在拖动实现了,用的renderjs,页面元素的touchmove事件传给renderjs里的处理函数,但是touchmove的同时会造成页面滚动,影响使用,调用事件参数的preventDefault()没有用,@touchmove.stop.prevent或者@touchmove.stop或者@touchmove.prevent页面是不滚动了,但是监听函数也直接就不触发了,怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊怎么搞啊好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急好急
1***@qq.com
- 发布:2024-03-20 18:24
- 更新:2024-03-20 20:38
- 阅读:174
1***@qq.com (作者)
最外层container我给它高度200%以让它能上下滚动,我期望是:手指在canvas所在的区域滑动的时候,能触发我的ontouchmove,而页面不滚动
<template>
<view class="container" >
<view
id="content"
style="width: 400rpx; height: 400rpx; box-sizing: border-box; border: 1rpx solid black;"
@touchmove="m.ontouchmove"
@touchend="m.ontouchend"
@touchcancel="m.ontouchend">
</view>
</view>
</template>
<script module="m" lang="renderjs">
let prevX = null, prevY = null
let translateX = 0, translateY = 0
let animationId
let canvas, ctx, dpr
function frame() {
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.setTransform(1, 0, 0, 1, translateX, translateY)
ctx.fillRect(50, 50, 100, 100)
animationId = null
}
export default {
mounted() {
const content = document.getElementById('content')
canvas = document.createElement('canvas')
ctx = canvas.getContext('2d')
// Get the DPR and size of the canvas
dpr = window.devicePixelRatio;
const rect = content.getBoundingClientRect();
// Set the "actual" size of the canvas
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Scale the context to ensure correct drawing operations
ctx.scale(dpr, dpr);
// Set the "drawn" size of the canvas
canvas.style.width = `${rect.width}px`;
canvas.style.height = `${rect.height}px`;
content.appendChild(canvas)
frame()
},
methods: {
ontouchmove(e) {
const touches = e.touches
const mX = touches[0].clientX
const mY = touches[0].clientY
if (!prevX || !prevY) {
prevX = mX
prevY = mY
return
}
translateX += (mX - prevX) * dpr
translateY += (mY - prevY) * dpr
prevX = mX
prevY = mY
if (animationId) cancelAnimationFrame(animationId)
animationId = requestAnimationFrame(frame)
},
ontouchend() {
prevX = null
prevY = null
}
}
}
</script>
<style>
.container {
width: 100%;
height: 200%;
}
</style>
1***@qq.com (作者)
尝试过了,我就是这样做的,canvas我是在rendejs里通过document.createElement的方式创建的,然后append到它的父节点上,不过对应的函数没有执行
2024-03-20 19:29
JXWang
回复 1***@qq.com: 可否上传个简单的可复现的demo工程
2024-03-20 19:40
1***@qq.com (作者)
回复 JXWang: 好的
2024-03-20 20:20
1***@qq.com (作者)
回复 JXWang: 我回复到下面的评论了
2024-03-20 20:38
1***@qq.com (作者)
回复 JXWang: 没事了,解决了,给canvas父元素addEventListener,就可以调用preventDefault()了
2024-03-21 10:05
JXWang
回复 1***@qq.com: 好的,解决了就好
2024-03-21 10:09