Fabric.js 使用HTML的图片

方法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; 把图片隐藏起来。

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!