如何使用GrapesJS构建web编辑器1.图片?的写作风格

优采云 发布时间: 2021-08-12 19:27

  

如何使用GrapesJS构建web编辑器1.图片?的写作风格

  

  按照我平时的写作风格,我将文章的大纲列在下面,以便大家有选择性地高效阅读和学习:

  基本介绍

  

  chrome-capture.gif

  乍一看,我们可能认为它只是一个页面/HTML 编辑器,但它可以做的远不止这些。 GrapesJS 是一个多用途的网页构建框架,这意味着它允许我们轻松创建任何支持拖放的构建器,具有类似的 HTML 结构。它收录的不仅仅是网页。我们使用类似 HTML 的结构的场景是:

  GrapesJS 中收录的功能和工具使我们能够制作一个易于使用的编辑器。这使用户无需任何编码知识即可创建复杂的类似 HTML 的模板。

  同时GrapesJS官网也为我们提供了3种不同的场景,大家可以参考这些案例快速制作自己的网页编辑器:

  所以对于这些框架的实现原理,我在之前的文章中也做了很多分析和设计。有兴趣的可以参考一下,研究一下。接下来,我们来看看如何安装和使用。

  如何使用 GrapesJS 构建网页编辑器

  1.安装

  我们可以使用 umd 导入:

    

  也可以通过 npm 安装:

  npm i grapesjs -S 

  之后,我们可以通过以下方式导入到项目中:

  import 'grapesjs/dist/css/grapes.min.css'; import grapesjs from 'grapesjs'; 

  2. 第一个演示

  安装完成后,我们先实现一个基本的页面编辑演示:

  

  chrome-capture (1).gif

  相关代码如下:

                             #gjs {           border: 3px solid #444;         }         .gjs-cv-canvas {           top: 0;           width: 100%;           height: 100%;         }                       Hello World Component!                  const editor = grapesjs.init({           container: '#gjs',           // 我们也可以使用可选的: `components: 'Hello World Component!'`,           fromElement: true,           // 编辑器尺寸           height: '300px',           width: 'auto',           // 禁用存储管理, 下面的文章我会介绍           storageManager: false,           panels: { defaults: [] },          });          

  这样就实现了一个简单的编辑器。是不是很简单?让我们继续探索更强大的功能。

  3. 添加和定义组件

  我们都知道网页编辑器需要提供非常丰富的组件集,可以帮助用户更轻松地构建页面。同样,grapesjs 支持添加各种自定义组件,也内置了通用的基础组件。我们来看一个演示:

  

  chrome-capture (2).gif

  从上面的demo中我们可以看到增加了3个基本组件:块、文本和图片。基本实现代码如下:

  const editor = grapesjs.init({   // ...其他配置   blockManager: {     appendTo: '#blocks',     blocks: [       {         id: 'section',         label: 'Section',          attributes: { class:'gjs-block-section' },         content: `           H5-Dooring           积木式搭建H5页面         `,       }, {         id: 'text',         label: 'Text',         content: 'My Baby',       }, {         id: 'image',         label: 'Image',         select: true,         content: { type: 'image' },         activate: true,       }     ]   }, }); 

  从代码中我们可以发现,我们只需要在blockManager的blocks中添加指定的组件即可。同时,我们也可以动态添加组件:

  editor.BlockManager.add('my-block-id', {     // ...其他配置如label     content: {         tagName: 'div',         draggable: false,         attributes: { 'some-attribute': 'some-value' },         components: [           {             tagName: 'span',             content: 'DooringX',           }, {             tagName: 'div',             components: '无限可能',           }         ]       } }) 

  更详细的组件配置文档可以参考文档:Howgrassjs component works

  

  图像.png

  4.添加功能面板

  仅仅添加组件是不够的。一个端庄的编辑器还应该有各种功能按钮,以满足不同用户的需求。

  现在我们有了画布和自定义组件,让我们看看如何创建一个带有按钮的功能面板(使用 Panels API)。

  

  chrome-capture (3).gif

  我们可以看到顶部有3个功能按钮:

  首先我们需要定义用于显示功能面板的元素(样式可以自定义):

         

  接下来,让我们定义安装功能面板:

  editor.Panels.addPanel({   id: 'panel-top',   el: '.panel__top', }); editor.Panels.addPanel({   id: 'basic-actions',   el: '.panel__basic-actions',   buttons: [     {       id: 'visibility',       active: true,       className: 'btn-toggle-borders',       label: 'B',       command: 'sw-visibility',     }, {       id: 'export',       className: 'btn-open-export',       label: 'Exp',       command: 'export-template',       context: 'export-template',      }, {       id: 'show-json',       className: 'btn-show-json',       label: 'JSON',       context: 'show-json',       command(editor) {         editor.Modal.setTitle('Components JSON')           .setContent(`             ${JSON.stringify(editor.getComponents())}           `)           .open();       },     }   ], }); 

  我们可以定义更多的函数,可以参考文档学习使用。

  5. 添加图层管理面板

  在处理网页元素时,我们可能会发现另一个常用的工具是图层管理器​​。它是一个树状结构,让我们可以轻松管理页面元素。要启用它,我们只需要指定在哪里渲染它:

  const editor = grapesjs.init({   // ...   layerManager: {     appendTo: '.layers-container'   },   // 我们能定义一个默认的面板作为侧边图层管理器   panels: {     defaults: [{       id: 'layers',       el: '.panel__right',       // 定义面板能否拖拽       resizable: {         maxDim: 350,         minDim: 200,         tc: 0,         cl: 1, // 左侧可拖拽         cr: 0,         bc: 0,         keyWidth: 'flex-basis',       },     }]   } }); 

  效果如下:

  

  chrome-capture (4).gif

  我们可以在右侧看到图层面板,我们可以轻松管理页面上的元素。

  6.添加样式配置面板

  样式面板也很简单,我们先定义对应的容器:

              

  然后初始化相应的配置脚本:

  const editor = grapesjs.init({   // ...   panels: {     defaults: [       // ...       {         id: 'panel-switcher',         el: '.panel__switcher',         buttons: [{             id: 'show-layers',             active: true,             label: 'Layers',             command: 'show-layers',             // Once activated disable the possibility to turn it off             togglable: false,           }, {             id: 'show-style',             active: true,             label: 'Styles',             command: 'show-styles',             togglable: false,         }],       }     ]   },   selectorManager: {     appendTo: '.styles-container'   },   styleManager: {     appendTo: '.styles-container',     sectors: [{         name: 'Dimension',         open: false,         buildProps: ['width', 'min-height', 'padding'],         properties: [           {             type: 'integer',             name: 'The width',             property: 'width',              units: ['px', '%'],              defaults: 'auto',              min: 0,            }         ]       },{         name: 'Extra',         open: false,         buildProps: ['background-color', 'box-shadow', 'custom-prop'],         properties: [           {             id: 'custom-prop',             name: 'Custom Label',             property: 'font-size',             type: 'select',             defaults: '32px',             options: [               { value: '12px', name: 'Tiny' },               { value: '18px', name: 'Medium' },               { value: '32px', name: 'Big' },             ],          }         ]       }]   }, });  // 定义指令 editor.Commands.add('show-layers', {   getRowEl(editor) { return editor.getContainer().closest('.editor-row'); },   getLayersEl(row) { return row.querySelector('.layers-container') },    run(editor, sender) {     const lmEl = this.getLayersEl(this.getRowEl(editor));     lmEl.style.display = '';   },   stop(editor, sender) {     const lmEl = this.getLayersEl(this.getRowEl(editor));     lmEl.style.display = 'none';   }, }); editor.Commands.add('show-styles', {   getRowEl(editor) { return editor.getContainer().closest('.editor-row'); },   getStyleEl(row) { return row.querySelector('.styles-container') },    run(editor, sender) {     const smEl = this.getStyleEl(this.getRowEl(editor));     smEl.style.display = '';   },   stop(editor, sender) {     const smEl = this.getStyleEl(this.getRowEl(editor));     smEl.style.display = 'none';   }, }); 

  我们可以看到配置后的效果:

  

  chrome-capture (5).gif

  7.更多使用演示

  除了上面介绍的功能,我们还可以实现:

  这里就不一一介绍了,来看看配置后的演示效果:

  

  chrome-capture (6).gif

  craft.js,一个基于 GrapesJS 构建的开源网页编辑器

  然后 GrapesJS 有许多有趣的功能我们可以探索。接下来给大家分享一个基于GrapesJS二次打包的开源编辑器框架craft.js。

  

  chrome-capture (7).gif

  我们可以用它来构建我们自己的编辑器插件。以下是在 React 中的应用示例:

  import {Editor, Frame, Canvas, Selector} from "@craftjs/core"; // 定义本文组件 import {useNode} from "@craftjs/core";  const TextComponent = ({text}) => {   const { connectors: {drag} } = useNode();    return (            {text}        ) }  // 初始化编辑器 const App = () => {   return (                     // 可编辑的区域                                                                    ) } 

  更多视觉编辑器推荐

  终于

  后期会在数据可视化和工程方面输出更多实用的开源项目和框架。如有其他问题或需求,可与作者交流。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线