LoginSignup
4
6

More than 1 year has passed since last update.

Nuxt+fabric.jsで画像同士を重ね合わせるcanvasを作成

Last updated at Posted at 2021-10-16

pngなどの透過画像をcanvasで重ねたかったのですが、いい感じのまとまった記事がなかったのでこちらでまとめています。

しかも自分の重ねたい方法は、操作している画像が固定されている画像の下に常に存在するようにする、というもので見つけるのが大変でした。フレーム画像の下で画像編集をしたいときなどに使えると思います。

前提

  • nuxt-composition-apiをインストールして準備していること
  • fabric.jsをインストールして準備していること

使った画像

透過画像はこちらで手に入れました。

コード

鍵となるのは globalCompositeOperation です。これを見つけるのにすごく時間がかかりました、、、
destination-overをつかうことによって、元からある図形の下に描画ができるようになります。また、一番上の画像は今回selectableを解除しています。

index.vue
<template>
  <div>
    <h1>画像編集ページ</h1>
    <div class="wrapper">
      <canvas id="canvas" width="300" height="300" />
    </div>
  </div>
</template>

<script lang="js">
import { onMounted, computed, defineComponent } from '@nuxtjs/composition-api'
import { fabric } from 'fabric'

export default defineComponent({
  setup() {
    const canvas = computed(() => new fabric.Canvas('canvas'))

    onMounted(() => {
      // globalCompositeOperation: https://stackoverflow.com/questions/43455582/how-correctly-apply-globalcompositeoperation-on-canvass-elements
      fabric.Image.fromURL(
        require('~/assets/images/sample/ocean.png'),
        myImg => {
          // i create an extra var for to change some image properties
          myImg.scaleToWidth(canvas.value.getWidth())
          myImg.set(
            {
              left: 0,
              top: 0,
              width: 2000,
              height: 2000,
              selectable: false,
            }
          )
          canvas.value.add(myImg)
        }
      )
      fabric.Image.fromURL(
        require('~/assets/images/sample/seagull.png'),
        myImg => {
          // i create an extra var for to change some image properties
          myImg.scaleToWidth(canvas.value.getWidth())
          myImg.set(
            {
              left: 100,
              top: 100,
              width: 1000,
              height: 1000,
              globalCompositeOperation: 'destination-over',
            }
          )
          canvas.value.add(myImg)
        }
      )
    })

    return { }
  },
})
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
  border: 1px solid;
}
</style>

結果

Image from iOS (1).jpg

参考

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6