添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
满身肌肉的小刀  ·  2016-2021 Mercedes ...·  3 周前    · 
率性的稀饭  ·  spark-plan/article/201 ...·  4 月前    · 
坐怀不乱的大葱  ·  "variable is not set. ...·  6 月前    · 
温暖的芒果  ·  沙漠女王 - 知乎·  1 年前    · 
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>
        <h1>画像編集ページ</h1>
        <div class="wrapper">
          <canvas id="canvas" width="300" height="300" />
    </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>
    

    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
    6