Fabric.js 使用HTML的图片

JavaScript/前端
326
0
0
2022-11-08
标签   JavaScript库

方法1:使用HTML的图片

Fabric.js 使用HTML的图片

<template> 
  <div> 
    <canvas width="400" height="400" id="canvas" style="border: 1px solid #ccc;"></canvas> 
    <img src="@/assets/logo.png" id="logo"> 
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'

function init() {
  const canvas = new fabric.Canvas('canvas')

  const imgElement = document.getElementById('logo')

  imgElement.onload = function() {
    let imgInstance = new fabric.Image(imgElement, {
      left: 100,
      top: 100,
      width: 200,
      height: 200,
      angle: 50, // 旋转
    })
    canvas.add(imgInstance)
  }

}

onMounted(() => {
  init()
})
</script>

<style>
#logo {
  display: none;
}
</style>

需要使用 onload 方法监听图片是否加载完成。

只有在图片完全加载后再添加到画布上才能展示出来。

使用该方法,如果不想在画布外展示图片,需要使用 display: none; 把图片隐藏起来。