前端开发Vue + Fabric.js + Element-plus 实现简易的H5可视化图片编辑器

Posted 李猫er

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端开发Vue + Fabric.js + Element-plus 实现简易的H5可视化图片编辑器相关的知识,希望对你有一定的参考价值。

前言

canves 绘图的运用是前端必知必会的基础,但是canves 本身并不好用,而fabric.js是基于canves的一个绘图框架库,用起来可比canves友好多了!接下来带你看看案例和初识fabric.js~

一 、实战效果

编辑前:

编辑中:

技术选型

  • Vue3
  • Element-plus
  • Fabric.js
  • ES6

核心功能

主要实现H5 移动端简单的图片的可视化编辑、预览、下载等功能。

  • 文本编辑:实现画布上的文本框的添加、字体属性的设置、样式风格编辑、背景颜色个性化设置、文本内容的设置等;
  • 图片上传:点击上传图片,实现图片的读取并添加到画布编辑区上,自由设置背景图片;
  • 绘制图片:实现根据鼠标坐标自由绘制图形(目前仅实现矩形,其他类似,可参考fabric 文档说明自己实现);
  • 删除控件:编辑区上的控件可自由删除;
  • 预览图片:编辑完成后可预览自己编辑的图片效果,并在右侧100%显示;
  • 下载图片:可下载编辑好的图片;
  • 画布缩放:可放大或者缩小画布,画布上的内容同步缩放;
  • 一键清空:重置实现画布一键清空;

目前仅实现以上的功能,后续在继续完善更新~~

代码实现

editor.vue:

<template>
  <el-container >
    <el-header >
      <el-menu
        style="background: #6A60E3"
        mode="horizontal"
      >
        <div style="width: 400px; float: left;height:70px;color: #fff; background: #5951B6;line-height: 70px">
          <h1 style="text-align: center">{{ templatesTitle }}</h1>
        </div>
        <el-form inline="inline" style="float: right; width: 1000px" >
          <el-button
              class="el-icon-plus btn_style" style="width: 140px"
              @click="addTextHandle('textbox', 'add')"
          > 添加文本框
          </el-button>
          <el-button class="el-icon-plus btn_style" @click="imgDraw" >
            <input type="file" accept="image/*"
                style="display:none"
                id="uploadfile"
                @change="uploadFile" />
            上传图片
          </el-button>
          <el-button class="el-icon-edit btn_style"
              @click="initD"
          >   绘 制 </el-button>
          <el-button
            class="btn-delete btn_style el-icon-delete"
            @click="deleteText"
          > 删除控件
          </el-button>
        </el-form>
      </el-menu>
    </el-header>
    <el-container>
      <el-aside :width="isCollapsed ? '30px' : '300px'">
        <div class="text-edit">
          <div
            @click="closeSetting"
            class="title-setting"
            :tipTitle="isCollapsed ? '展开设置' : '收起设置'"
          >
            <span class="text-setting">{{ title }}</span>
            <i :class="isCollapsed ? 'el-icon-s-unfold' : 'el-icon-close'"/>
          </div>
          <el-form ref="form" >
            <el-form-item label="文本内容:">
              <div id="textBox"  style="width: 100% ">
                <el-input type="textarea"
                    @input="changeText"
                    @focus="changeText"
                    id="in" ref="in"
                    v-model="msg" ></el-input>
              </div>
            </el-form-item>
            <el-form-item label="字体:" label-width="82px">
              <el-select  v-model="fontFamilies.value"
                  placeholder="请选择字体"
                  @change="changeFontFamily">
                <el-option
                  v-for="item in fontFamilies"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体颜色:" >
              <el-select v-model="fontColor.value"
              placeholder="请选择字体颜色"
                  @change="changeFontColor"
              >
                <el-option
                  v-for="item in fontColor"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体粗细:" >
              <el-select v-model="fontWeight.value"
              placeholder="请选择字体粗细"
                  @change="changefontWeight"
              >
                <el-option
                  v-for="item in fontWeight"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体风格:" >
              <el-select v-model="fontStyle.value"
              placeholder="请选择字体风格"
                  @change="changeFontStyle">
                <el-option
                  v-for="item in fontStyle"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体大小:" >
              <el-select v-model="fontSizes.value"
              placeholder="选择字体大小"
                  @change="changeFontSize">
                <el-option
                  v-for="item in fontSizes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="对齐方式:" >
              <el-select v-model="textAlign.value"
                  @change="changeTextAlign"
                  placeholder="选择对齐方式">
                <el-option
                  v-for="item in textAlign"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="背景颜色:" >
              <el-color-picker
                class="color-picker"
                v-model="bgcolor" circle
                size="small"
                show-alpha
                :predefine="predefineColors"
                @change="changeBgColor"
                color-format="hex"
              ></el-color-picker>
            </el-form-item>
            <el-form-item>
<!--              <ul class="template-edit" id="template-edit" @click="chooseTemplate">
                <li><img src="@/assets/logo.png" alt="" id="bg1"  style="width: 100px;height: 50px" /></li>
                <li><img src="@/assets/logo.png" alt="" id="bg2"  style="width: 100px;height: 50px" /></li>
                <li><img src="@/assets/logo.png" alt="" id="bg3"  style="width: 100px;height: 50px" /></li>
              </ul>-->
            </el-form-item>
          </el-form>
        </div>
      </el-aside>
      <el-main style="height: 1040px" >
        <div class="content-show">
          <div class="canvas">
          <canvas ref="canvas" id="editorCanvas"></canvas>
        </div>
        </div>
        <el-form class="handleSave">
          <el-button type="primary" class="btn-save" @click="downLoadImage1">预览图片</el-button>
          <el-button type="primary" class="btn-download" @click="downLoad">下载图片</el-button>
          <el-form-item inline="inline" class="btn-zoom" style="margin: 10px 0px">
            <i class="el-icon-caret-left" @click="zoomIt(0.8)"></i>
            <span> {{ zoomCounter }} % </span>
            <i class="el-icon-caret-right" @click="zoomIt(1.2)"></i>
          </el-form-item>
          <el-button type="danger" class="btn-reset" @click="resetCanvas">重 置</el-button>
        </el-form>
      </el-main>
      <el-aside :width="isCollapsed ? '30px' : '375px'">
        <div
          @click="closeSetting"
          class="title-setting"
          :tipTitle="isCollapsed ? '展开设置' : '收起设置'"
        >
          <span class="text-setting">{{ showTitle }}</span>
          <i :class="isCollapsed ? 'el-icon-s-unfold' : 'el-icon-close'"/>
        </div>
        <img :src="imageBase64" alt="">
      </el-aside>
    </el-container>
  </el-container>
</template>

<script>

  import {
    fontFamilies,
    fontSizes,
    fontColor,
    fontStyle,
    fontWeight,
    backgroundColor,
    textAlign,
  } from "@/utils/fontData";

  import { fabric } from "fabric";
  let editorCanvas = "";

  fabric.Object.prototype.set({
    cornerStrokeColor: "#66b0ef",
    cornerColor: "#60abec",
    cornerStyle: "rectangele",
    cornerSize: 8,
    borderScaleFactor: 2,
    transparentCorners: false,
    borderColor: "#61abe8",
  });

  export default {
    name: "Editor",
    data() {
      return {
        isHide: true,
        checkAll: false,
        isChecked:false,
        isIndeterminate: true,
        fontFamilies,
        fontSizes,
        fontColor,
        fontStyle,
        fontWeight,
        textAlign,
        backgroundColor,
        predefineColors: ["#ffffff", "#FF0000", "#000000","#FFF800","#00FF0A","#FD00FF","#0095FF"],
        checked: true,
        // 模板图片保存数组
        templateImgs: [],
        zoomCounter: 100,
        tipTitle: "",
        imageBase64: "",
        isCollapsed: false,
        backColor: "#eec5c5",
        backGroundStatus: false,
        bgcolor: "#ff0000",
        itemWidth: "230px",
        done: false,
        // 文本控件属性
        textStyleData: {
          type: "editText",
          text: "双击编辑文字",
          top: 50,
          left: 50,
          width: 100,
          opacity: 1,
          stroke: "#ffffff",
          strokeWidth: 0,
          textAlign: "left",
          lineHeight: 1,
          charSpacing: 1,
          fontFamily: "hyzktjjkt",
          fontSize: 40,
          fontWeight: "normal",
          fontStyle: "normal",
          fill: "#000000",
          textBackgroundColor: "rgba(0,0,0,0)",
          selectable: true,
        },
        isOpen: false,
        isMove: false,
        src: "",
        msg: "",
        canvas: null,
        templatesTitle: "H5 可视化编辑",
        title: "文本设置",
        showTitle:"100% 预览",
        templateData: {},
        mouseFrom: {},
        mouseTo: {},
        moveCount: 1,
      };
    },
    mounted() {
      this.initeditorCanvas();
    },
    methods: {
      downLoadImage1() {
        this.done = true
        let base64URl = editorCanvas.toDataURL({
          formart: 'png',
          multiplier: 1
        })
        this.imageBase64 = base64URl
        this.done = false
      },

      saveTemplates() {
        console.log("你点击了模板保存");
        let base64URl = editorCanvas.toDataURL({
          formart: "jpg",
          multiplier: 1,
        });
      },

      addTemplates() {
        console.log("添加模板");
      },

      initD() {
        // 监听鼠标按下
        const obj = editorCanvas.getActiveObject();
        editorCanvas.on("mouse:down", (options) => {
          // 记录当前鼠标的起点坐标
          if(!obj) {
            this.mouseFrom.x = options.e.clientX - editorCanvas._offset.left;
            this.mouseFrom.y = options.e.clientY - editorCanvas._offset.top;
          }
        });
        // 监听鼠标移动
        editorCanvas.on("mouse:move", (options) => {
          // 记录当前鼠标移动终点坐标
          if (!obj) {
            this.mouseTo.x = options.e.clientX - editorCanvas._offset.left
            this.mouseTo.y = options.e.clientY - editorCanvas._offset.top
            this.drawRect();
          }
        });
        editorCanvas.on("mouse:up", (options) => {
          if (!obj) {
            this.mouseFrom.x = options.e.clientX - editorCanvas._offset.left;
            this.mouseFrom.y = options.e.clientY - editorCanvas._offset.top;
            this.doDrawing = false;
            this.canvasObject = null;
            this.mouseFrom = {};
            this.mouseTo = {}
          }
        });
        editorCanvas.on("selection:created",(option) => {
          if (option) {
            this.doDrawing = false;
          }
        })
      },
      getTransformedPosX(x) {
        let zoom = Number以上是关于前端开发Vue + Fabric.js + Element-plus 实现简易的H5可视化图片编辑器的主要内容,如果未能解决你的问题,请参考以下文章

前端Vue框架 04 路由:逻辑跳转路由传参 项目组件的数据局部化处理data(){ return{} } 组件的声明周期 组件间通信 各种第三方插件(vuex,axios,ele(

在线教育_Day05-项目讲师管理模块前端开发

canvas库fabric.js踩坑

vue2 + fabric.js 实现撤销恢复效果

Vue--vue+elementUI开发示例

堡垒机项目实战-批量任务的前端页面开发