收藏
回答

Canvas真机调试不显示,开发工具中正常为啥?

https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Canvas.html

这个页面中的“2D Canvas 示例“

在开发者工具中正常,真机调试就出现错误不显示

代码就是实例代码,没有任何改动

const app = getApp()


Page({
  data: {},


  onLoad: function () {
    this.position = {
      x: 150,
      y: 150,
      vx: 2,
      vy: 2
    }
    this.x = -100


    // 通过 SelectorQuery 获取 Canvas 节点
    wx.createSelectorQuery()
      .select('#canvas')
      .fields({
        node: true,
        size: true,
      })
      .exec(this.init.bind(this))
  },


  init(res) {
    const width = res[0].width
    const height = res[0].height


    const canvas = res[0].node
    const ctx = canvas.getContext('2d')


    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)


    const renderLoop = () => {
      this.render(canvas, ctx)
      canvas.requestAnimationFrame(renderLoop)
    }
    canvas.requestAnimationFrame(renderLoop)


    const img = canvas.createImage()
    img.onload = () => {
      this._img = img
    }
    img.src = './car.png'
  },


  render(canvas, ctx) {
    ctx.clearRect(00300300)
    this.drawBall(ctx)
    this.drawCar(ctx)
  },


  drawBall(ctx) {
    const p = this.position
    p.x += p.vx
    p.y += p.vy
    if (p.x >= 300) {
      p.vx = -2
    }
    if (p.x <= 7) {
      p.vx = 2
    }
    if (p.y >= 300) {
      p.vy = -2
    }
    if (p.y <= 7) {
      p.vy = 2
    }


    function ball(x, y) {
      ctx.beginPath()
      ctx.arc(x, y, 50, Math.PI * 2)
      ctx.fillStyle = '#1aad19'
      ctx.strokeStyle = 'rgba(1,1,1,0)'
      ctx.fill()
      ctx.stroke()
    }


    ball(p.x, 150)
    ball(150, p.y)
    ball(300 - p.x, 150)
    ball(150300 - p.y)
    ball(p.x, p.y)
    ball(300 - p.x, 300 - p.y)
    ball(p.x, 300 - p.y)
    ball(300 - p.x, p.y)
  },


  drawCar(ctx) {
    if (!this._img) return
    if (this.x > 350) {
      this.x = -100
    }
    ctx.drawImage(this._img, this.x++, 150 - 2510050)
    ctx.restore()
  }
})
回答关注问题邀请回答
收藏

1 个回答

  • OREO(`・ω・´)
    OREO(`・ω・´)
    2021-09-23

    这个好像是微信小程序的真机测试环境问题,你在canvas标签里加入这个试试:

    force-use-old-canvas="true"


    2021-09-23
    有用 1
    回复
登录 后发表内容