How to add a block to the workspace without toolbox

1,356 views
Skip to first unread message

Eryn Kim

unread,
Apr 23, 2017, 10:57:15 PM4/23/17
to Blockly
Hi, I want to add a block by code not using the toolbox. Actually I'm trying to handle blocks with events that occurred outside of blockly.
So I referred to this page https://developers.google.com/blockly/reference/js/Blockly.Events.Create but there is no sample code and I have no idea how to use the api. 
And I'm afraid this page is right I have to refer. 


Sethuraman

unread,
Apr 24, 2017, 8:32:52 AM4/24/17
to Blockly
Hi 

   First you need to know the block name what you have to add to workspace

  var workspace = "Myworksapce" // your current workspace name what you given
  var blockName = " if-creator" // Name of block to add

  var newBlock = workspace.newBlock(blockName);
  newBlock.initSvg();
  newBlock.render();

 you will see the block that you created in workspace 

Eryn Kim

unread,
Apr 26, 2017, 5:24:30 AM4/26/17
to Blockly
Wow. It works perfectly. Thank you!! :) 

Eryn Kim

unread,
Apr 27, 2017, 12:46:14 AM4/27/17
to Blockly
One more thing, I have added a block programatically and I set the value of block like below.

newBlock.setFieldValue('hello', 'block_name');

And I want to set values of properties of block. For example, the properties of the image block are src, width, height and alt.
How can I do this?

Sethuraman

unread,
Apr 27, 2017, 6:41:49 AM4/27/17
to Blockly
HI

   Iam not sure how to change the svg content -- all the controll what we create in blockly Workspace will render as an svg element , 
   I have tried for changing the html element of image and its working , but if we save the xml and restore its not retaining the value .

   For changing the property of image while creating you should give the name for image .

  Blockly.Blocks['image_type'] = {
  init: function() {
    this.appendDummyInput()
        .appendField(new Blockly.FieldImage("https://www.gstatic.com/codesite/ph/images/star_on.gif", 15, 15, "*"),"myimage");
    this.setColour(230);
    this.setTooltip('');
    this.setHelpUrl('');
  }
};


Blockly.JavaScript['image_type'] = function(block) {
  // TODO: Assemble JavaScript into code variable.
  var code = '...;\n';
  return code;
};

 after you render the block in workspace 

var allblocks = Blockly.mainWorkspace.getAllBlocks()

this will have all blocks and know the block name or block id loop in allblocks get the block detail , for now if we render only one block i take position 0 as reference 

var myfield = allblocks[0].getField("myimage");
myfield.imageElement_.style.width = "30px"
myfield.imageElement_.style.height = "30px"

then the image will increase or decrease according to it 

through this you can add any html events to element 

myfield.imageElement_.onmouseover = function(e){console.log("mouse event ")};


Reply all
Reply to author
Forward
0 new messages