小程序 canvas 绘图偏移怎么办? style 设置宽高不好使怎么办?什么是显示设置宽高

484 阅读1分钟

什么是显示设置宽高

image.png

直接上代码

// canvas/progressBar/progressBar.ts

Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {

    },

    lifetimes: {
        // created:function() {
        //  // 在组件实例进入页面节点树时执行
        //  this.getCanvasIntace();
        // },
        ready:function() {
            // 在组件实例进入页面节点树时执行
            this.getCanvasIntace();
           },
        attached: function() {
 
        },
        detached: function() {
          // 在组件实例被从页面节点树移除时执行
        },
      },


    /**
     * 组件的方法列表
     */
    methods: {
    // 获取canvas 实例
   async getCanvasIntace() {
        // 通过 SelectorQuery 获取 Canvas 节点
        this.createSelectorQuery().select("#myProcessCanvas").fields({ node: true, size: true }).exec(res => this.init(res));
     
    },
    init (res: any) {
      const {width ,height} = res[0];
 
      const dpr = wx.getSystemInfoSync().pixelRatio
      console.log("不带闯将的",width,height,dpr)
        const y = 20;
        const x = 0;
        const top = 5;
        const loop = 5;
        const lineWidth = 2;
         const canvas = res[0].node;
         canvas.width = width;
         canvas.height = height;
         const ctx : CanvasRenderingContext2D   = canvas.getContext('2d');
         const stack = this.setLine(loop,x,y,top,width,lineWidth);
         ctx.lineWidth = lineWidth;
        ctx.strokeStyle = '#B3B3B3';
        ctx.font="15"
        ctx.beginPath();
        for(let i=0;i<stack.length;i++) {
          ctx.moveTo(...stack[i][0]);
          ctx.lineTo(...stack[i][1]);
           }
      
        ctx.moveTo(x+lineWidth,y);
        ctx.lineTo(width-lineWidth,y);
        ctx.stroke();
  
    },
    canvasIdErrorCallback (error :any) {
      console.error(error);
    },
    /**
     * 
     * @param loop 时长均分播放条
     * @param x 坐标x 初始值
     * @param y 坐标y 初始值
     * @param top 距离顶部高度
     */
   setLine(loop :number = 5,x:number = 5,y:number = 5,top:number = 40,width :number = 0,lineWidth:number=0) {
      const stack : Array<[[number,number],[number,number]]> = [];
      const length = loop*4
      const skep = width/length;
     
      for(let i=0;i<length;i++) {
     
        if(i%4 === 0) {
          if(i===0) {
            stack.push([
              [skep*i+lineWidth,y],
              [skep*i+lineWidth,top]
            ]);
          } else {
            stack.push([
              [skep*i,y],
              [skep*i,top]
            ]);
          }
    
        } else {
          stack.push([
            [skep*i,y],
            [skep*i,top+6]
          ]);
          
        }


     }

    stack.push([[skep*(length)-lineWidth,y],[skep*(length)-lineWidth,top]]);
      
     return stack;
    }
    },

 

})


其中 canvas.width = width; canvas.height = height;即为显示设置宽高,可修复小程序canvas 画图模糊,位置便宜等问题 代码执行效果如图

image.png