Search code examples
vue.jscanvasfabricjselectron-builderkonva

Canvas not drawing images - Electron + Vue


I'm trying to draw images in my canvas, but for some reason it's not working. I've tried with default canvas API, KonvaJS and FabricJS, but none of these worked. Other shapes like rects, circles etc works normaly...

My project is an electron app built with electron-builder via Vue Cli.

Code with default canvas API:

<template>
  <div>
    <canvas ref="cnv" width="500" height="500"></canvas>
  </div>
</template>

<script>
export default {
  name: 'Test',
  mounted() {
    let cnv = document.querySelector("canvas");
    let ctx = cnv.getContext("2d");

    let img = new Image()
    img.src = "./img.png"

    img.onload = () => ctx.drawImage(img, 10, 10);
  }
}
</script>

Code with KonvaJS:

<template>
  <div id="cnv"></div>
</template>

<script>
import Konva from 'konva'

export default {
  name: 'Test',
  mounted() {
    let stage = new Konva.Stage({
      container: 'cnv',
      width: 500,
      height: 500,
    })

    let layer = new Konva.Layer()
    stage.add(layer)

    // Doesn't work with "fromUrl" method too
    let image = new Image()
    image.src = 'img.png'

    image.onload = () => {
      let img = new Konva.Image({
        x: 20,
        y: 20,
        width: 32,
        height: 48,
        image: image,
      })

      layer.add(img)
      layer.draw()
    }
  }
}
</script>

Code with FabricJS:

<template>
  <div>
    <canvas ref="cnv" width="500" height="500"></canvas>
  </div>
</template>

<script>
import { fabric } from 'fabric'

export default {
  name: 'Test',
  mounted() {
    const ref = this.$refs.cnv
    const canvas = new fabric.Canvas(ref)

    fabric.Image.fromURL('img.png', function(img) {
      img.set({
        left: 20,
        top: 20,
      })

      canvas.add(img)
    })
  }
}
</script>

Example in CodeSandbox: draw-image-test

Is it something I'm doing wrong, or is this a vue problem?


Solution

  • I moved the "assets" folder to the "public" folder and it worked.

    correct