[Vuejs]-Drawing a box onto a Image with Vue and Bootstrap

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>

Leave a comment