亲爱的小伙伴,当你需要在uniapp中使用canvas绘制一个超长图,就类似于横向的流程图时,这个canvas超出屏幕部分拖动屏幕查看会变得十分棘手。我查阅了大量资料,甚至是问了无数遍ai,得到的结果只有很敷衍的监听touch,然后计算偏移量,然后重绘。可是,你想想,如果一次绘图里边有成百上千个元素,还有很大的图片,你重绘?那不得卡死。终于,在一次询问ai时给了我一丝曙光,并且实践告诉我,这个方法绝对管用!
1.使用scroll-view嵌套canvas,官网是说不许嵌套的,但是我们可以另辟蹊径,滚动的关键就再这个ontouchmove方法中
<scroll-view ref="scrollview" scroll-x scroll-y style="height: 100vh;" @touchmove="ontouchmove"> <canvas canvas-id="mycanvas" id="mycanvas" @tap="handlecanvastap" ref="mycanvas" style="width: 5000rpx; height: 200vh"></canvas> </scroll-view>
2.定义参数
data(){ retrun{ startx: 0, starty: 0, offsetx: 0, offsety: 0, context: null, endx: 0, endy: 0, ismoving: false, } }
3.关键方法
ontouchmove(e){ if (this.ismoving) { const deltax = e.touches[0].clientx - this.startx; const deltay = e.touches[0].clienty - this.starty; const query = uni.createselectorquery().in(this); query.select('#mycanvas').boundingclientrect().exec((res) => { const canvas = res[0].node; canvas.style.transform = `translate(${deltax}px, ${deltay}px)`; }); this.endx = e.touches[0].clientx; this.endy = e.touches[0].clienty; } }
4.你的canvas属性要跟的我一致,包你成功!
到此这篇关于uniapp中实现canvas超出屏幕滚动查看的文章就介绍到这了,更多相关uniapp canvas滚动查看内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论