开门见山,我们直接开始主题!
自定义类别
为了创建自定义类别,先创建一个自定义类 CustomCategory,并且让这个类继承 Blockly.ToolboxCategory
class CustomCategory extends Blockly.ToolboxCategory { // 自定义类别创造函数 /* categoryDef: 类别定义的信息 toolbox: 表示类别的父级toolbox opt_parent: 可选参数,表示其父类别 */ constructor(categoryDef, toolbox, opt_parent) { super(categoryDef, toolbox, opt_parent); }}其次呢,自定义类别需要向 Blockly 注册,告知自定义类别的存在,不然会无法识别新建的类
Blockly.registry.register(Blockly.registry.Type.TOOLBOX_ITEM, Blockly.ToolboxCategory.registrationName, CustomCategory, true);重写 createIconDom_方法
这个地方是关键!通过重写 createIconDom_方法,可以做到在 Category 当中展示自己定义的各种图标
往刚刚的 CustomCategory 类中重写 createIconDom_方法
class CustomCategory extends Blockly.ToolboxCategory { constructor(categoryDef, toolbox, opt_parent) { super(categoryDef, toolbox, opt_parent); }
createIconDom_() { // 这里新建了一个iconpark-icon元素,也可以自己修改为别的元素 const img = document.createElement("iconpark-icon"); // 这里的name属性获取的内容是toolbox定义的中的categorystyle,也可以是别的值/属性 img.name = this.toolboxItemDef_.categorystyle; // 设置图标大小 img.size = "21"; // 最后返回的应是一个元素 return img; }}其中 categorystyle 对应的是这个地方
{ "kind": "categoryToolbox", "contents": [ { "kind": "category", "name": "控制", "categorystyle": "controller", "contents": [ ...... ] } ]}<category name="Logic" categorystyle="logic_category"><!-- categorystyle: this.toolboxItemDef_.categorystyle调用 --></category>好,足足两步,你已经学会了在 Blockly 的 Toolbox 中使用 IconPark 图标!
效果预览


