微信小程序canvas内使用获取view元素宽高位置错

2023-03-01  本文已影响0人  adrainHsu

模拟器和手机都不一样。模拟器上,正常,手机上canvas内容都往右偏移了,反复实验发现:我canvas的宽高是获取的父级元素的宽高

<view class="abc"></view>
getCanvasWH(){
    let info = uni.createSelectorQuery().in(this).select(".abc");
    info.boundingClientRect(function(data) { 
          console.log(data.width)
          console.log(data.height)
    }).exec(function(res){
      // 注意:exec方法必须执行,哪怕什么也不做,否则会获取不到数据
    })
}
onReady (){
    this.getCanvasWH()
},
getCanvasWH(callback){
   setTimeout(()=>{
        let info = uni.createSelectorQuery().in(this).select(".abc");
        info.boundingClientRect(function(data) { 
            console.log(data.width)
            console.log(data.height)
            callback(data.width,data.height)
        }).exec(function(res){
        // 注意:exec方法必须执行,哪怕什么也不做,否则会获取不到数据
        })
    })
}

通过getCanvasWH的callback可以拿到宽高给canvas用

this.getCanvasWH((width,height)=>{
    // 在这里写canvas代码,width,height代过来了
})
上一篇 下一篇

猜你喜欢

热点阅读