Vue.js--TypeError:做画布时无法读取null的属性'getContext'

时间:2019-08-20 05:57:51

标签: vue.js canvas

我正在尝试在Vue上绘制画布,绘制一个矩形,它先在下面显示错误,然后以某种方式在某些时候起作用,但是当我添加另一个矩形时,它又显示了相同的错误。我很困惑。 [

TypeError: Cannot read property 'getContext' of null
    at VueComponent.draw (canvass.vue?0b9f:25)
    at Proxy.render (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"0ff045da-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/canvass.vue?vue&type=template&id=783d8a8a&scoped=true& (app.js:1258), <anonymous>:12:11)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3542)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4060)
    at Watcher.get (vue.runtime.esm.js?2b0e:4473)
    at new Watcher (vue.runtime.esm.js?2b0e:4462)
    at mountComponent (vue.runtime.esm.js?2b0e:4067)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8409)
    at init (vue.runtime.esm.js?2b0e:3118)
    at createComponent (vue.runtime.esm.js?2b0e:5972)

] 1

此外,我尝试使用let canvas = this.$refs.myCanvas而不是getElementById方法,因为它可能有效,但是没有运气。

<canvas id="canvas" ref="myCanvas" width="300" height="200" v-on="draw()"></canvas>

draw() {
      let canvas = document.getElementById('canvas')
      let c = canvas.getContext("2d");
      c.fillStyle = "rgba(255, 0, 0, 0.5)";
      c.fillRect(100, 50, 30, 30);
    }

1 个答案:

答案 0 :(得分:0)

Phil有正确答案。创建的生命周期挂钩在html和画布加载之前渲染。

您必须在已安装的挂钩中调用抽奖:

<canvas id="canvas" ref="myCanvas" width="300" height="200" </canvas>

mounted: function () {
 this.draw();
},

draw() {
  let canvas = document.getElementById('canvas')
  let c = canvas.getContext("2d");
  c.fillStyle = "rgba(255, 0, 0, 0.5)";
  c.fillRect(100, 50, 30, 30);
}