0

I am building an app where you can upload pictures, they are sent to a server where an object is detected on the image and the position of the object in the image is returnd. Now i want to mark the area with the detected object in the image, but i am struggeling with Javascript and Vue here a little bit.

Here is the code from my vue component:

<b-card title="Result" class="box">
        <span v-if="upload_success">
          <b-img v-bind:src="'http://localhost:5000/' + image_url" fluid-grow alt="Fluid-grow image" id="c"></b-img>
          <p>Category: {{ product_category }}</p>
        </span>
      </b-card>

and my draw method:

    draw () {
  let c = document.getElementById('c')
  let ctx = c.getContext('2d')
  this.canvas = ctx
  this.canvas.beginPath()
  this.canvas.rect(this.box[0], this.box[1], this.box[2], this.box[3])
  this.canvas.stroke()
}

testing this results in the following Error:

Uncaught (in promise) TypeError: c.getContext is not a function

pointing me to the draw function. what am i doing wrong here? thanks!!

stanleyyyyyy
  • 53
  • 1
  • 8

1 Answers1

0

The issue is that b-img renders a img tag, which you're trying to use canvas functions on. You could instead make a canvas that sits on-top of the image which you can then draw on, and it'll show like it's on the image since the canvas is transparent.

I'm not quite sure how it'll work since the image is fluid, and will try and fit it's container and change dynamically in width, so the canvas drawing might be misaligned.

new Vue({
  el: '#app',
  methods: {
    draw() {
      let c = this.$refs['myCanvas']
      const canvas = c.getContext('2d')
      canvas.beginPath()
      canvas.rect(20, 20, 150, 100)
      canvas.stroke()
    }
  }
})
.canvas-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  width: 100%;
  height: 100%
}

.canvas-wrapper {
  position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.5.0/dist/bootstrap-vue.min.js"></script>

<link href="https://unpkg.com/bootstrap-vue@2.0.0-rc.11/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap@4.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />

<div id="app">
  <b-container>
    <div class="canvas-wrapper">
      <b-img src="https://picsum.photos/600/300/?image=25" fluid-grow></b-img>
      <canvas ref="myCanvas" class="canvas-overlay"></canvas>
    </div>
    <b-btn @click="draw">Draw</b-btn>
  <b-container>
</div>
Hiws
  • 8,230
  • 1
  • 19
  • 36
  • 1
    @stanleyyyyyy Glad it worked out for you! You should set the answer as accepted :) – Hiws Mar 04 '20 at 14:29