前言
因为在网上没有找到太多相关的内容,所以自己整理了一篇文章
效果:
版本
blockly:12.1.0
操作
我们将用两个 SVG 文件替换 Blockly 默认垃圾桶的盖子和桶身图标:
/public/icon/trashcan_lid.svg
/public/icon/trashcan_body.svg
你可以用自己的图标文件替换这两个路径。 只要放置你们能拿到的位置,都可以 主要核心的代码其实就是替换垃圾桶图标的那一段代码
// 替换 Blockly 的垃圾桶图标
Blockly.Trashcan.prototype.createDom = function () {
this.svgGroup = Blockly.utils.dom.createSvgElement('g', { 'class': 'blocklyTrash' }, null);
const scale = 0.5;
// 替换桶盖
this.svgLid_ = Blockly.utils.dom.createSvgElement('image', {
'href': 'icon/trashcan_lid.svg',
'x': 0,
'y': 0,
'width': 80 * scale,
'height': 30 * scale
}, this.svgGroup);
// 替换桶身
this.svgBody_ = Blockly.utils.dom.createSvgElement('image', {
'href': 'icon/trashcan_body.svg',
'x': 0,
'y': 0, // y 要等于 lid 的高度,防止重叠
'width': 80 * scale,
'height': 80 * scale
}, this.svgGroup);
return this.svgGroup;
};
完整代码
<template>
<div>
<div ref="blocklyDiv" style="height: 800px; width: 100%; border: 1px solid #ccc;"></div>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import * as Blockly from 'blockly'
const blocklyDiv = ref()
const toolbox = {
kind: 'categoryToolbox',
contents: [
{
kind: 'category',
name: '逻辑',
colour: '#5CA65C',
contents: [
{
kind: 'block',
type: 'controls_if'
},
{
kind: 'block',
type: 'logic_compare'
}
]
},
{
kind: 'category',
name: '数学',
colour: '#5C81A6',
contents: [
{
kind: 'block',
type: 'math_number'
},
{
kind: 'block',
type: 'math_arithmetic'
}
]
}
]
}
// 替换 Blockly 的垃圾桶图标
Blockly.Trashcan.prototype.createDom = function () {
this.svgGroup = Blockly.utils.dom.createSvgElement('g', { 'class': 'blocklyTrash' }, null);
const scale = 0.5;
this.svgLid_ = Blockly.utils.dom.createSvgElement('image', {
'href': 'icon/trashcan_lid.svg',
'x': 0,
'y': 0,
'width': 80 * scale,
'height': 30 * scale
}, this.svgGroup);
this.svgBody_ = Blockly.utils.dom.createSvgElement('image', {
'href': 'icon/trashcan_body.svg',
'x': 0,
'y': 0, // y 要等于 lid 的高度,防止重叠
'width': 80 * scale,
'height': 80 * scale
}, this.svgGroup);
return this.svgGroup;
};
// 4. 初始化 Blockly
onMounted(() => {
Blockly.inject(blocklyDiv.value, {
toolbox,
trashcan: true,
})
})
</script>