Image fields

  • An image field stores an image's source as its value and an alt string as its text.

  • Image fields can be created using either JSON or JavaScript.

  • The image constructor accepts parameters for source, width, height, and optional alt text, click handler, and right-to-left flipping.

  • Image fields are not serializable.

  • Image fields can act like buttons using an on click handler function.

An image field stores a string as its value, and a string as its text. Its value is the src of the image, while its text is an alt string describing/representing the image.

Image field

A block with the label "image:" and an image of a yellow
star.

Image field on collapsed block

The same block after being collapsed. It has the label "variable: *", where
"*" is the alt text for the image, and a jagged right edge to show it is
collapsed.

Creation

JSON

{
  "type": "example_image",
  "message0": "image: %1",
  "args0": [
    {
      "type": "field_image",
      "src": "https://www.gstatic.com/codesite/ph/images/star_on.gif",
      "width": 15,
      "height": 15,
      "alt": "*"
    }
  ]
}

JavaScript

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

The image constructor takes in:

Parameter Description
src A string that points to a raster image file.
width Must cast to a non-zero number.
height Must cast to a non-zero number.
opt_alt (Optional) A string that accurately describes/represents the image. This is used instead of the image when the block is collapsed. If it is null or undefined an empty string will be used.
opt_onClick (Optional) A function to call when the field is clicked.
opt_flipRtl (Optional) A boolean. If true, the image is flipped across the vertical axis when in right-to-left mode. Defaults to false. Useful for "turn left" and "turn right" icons.

Serialization

Image fields are not serializable.

Click handler

The image field does not accept a validator; instead it explicitly accepts a function that is called whenever the field is clicked. This means that images can act like buttons that exist on blocks.

The on click handler can be set in the JavaScript Constructor or using the setOnClickHandler function.

Here is an example of an on click handler that collapses the block when called.

function() {
    this.getSourceBlock().setCollapsed(true);
}

An animated GIF showing the image being clicked, the block collapsing, a
right-click to display the context menu, Expand Block being chosen, and the
block being expanded.