[英]how to add a click event in blockly's blocks?
我正在按塊進行工作,遇到一種情況,即我有一個具有圖像的塊,我想單擊該圖像並觸發一個事件。 我不確定該怎么做。 我已經嘗試了blcokly的文檔,但是沒有提及。 它們僅在整個塊上提供onchange事件,而Image只是該塊的一部分。
任何想法我該如何實現?
提前致謝。
我有一個擴展field_image.js文件的想法,我繼承了必要的文件,並在init函數中在SVG元素中添加了一個eventlistenr。 這就是我使圖像可點擊的方式。 以下是代碼-
MyFieldImage.prototype = new Blockly.FieldImage();
MyFieldImage.prototype.constructor = MyFieldImage;
function MyFieldImage(src, width, height, opt_alt,isClickListener){
this.clickEventListener = isClickListener;
this.sourceBlock_ = null;
// Ensure height and width are numbers. Strings are bad at math.
this.height_ = Number(height);
this.width_ = Number(width);
this.size_ = new goog.math.Size(this.width_,
this.height_ + 2 * Blockly.BlockSvg.INLINE_PADDING_Y);
this.text_ = opt_alt || '';
this.setValue(src);
}
MyFieldImage.prototype.init = function(block) {
if (this.sourceBlock_) {
// Image has already been initialized once.
return;
}
this.sourceBlock_ = block;
// Build the DOM.
/** @type {SVGElement} */
this.fieldGroup_ = Blockly.createSvgElement('g', {}, null);
if (!this.visible_) {
this.fieldGroup_.style.display = 'none';
}
/** @type {SVGElement} */
this.imageElement_ = Blockly.createSvgElement('image',
{'height': this.height_ + 'px',
'width': this.width_ + 'px'}, this.fieldGroup_);
this.setValue(this.src_);
if (goog.userAgent.GECKO) {
/**
* Due to a Firefox bug which eats mouse events on image elements,
* a transparent rectangle needs to be placed on top of the image.
* @type {SVGElement}
*/
this.rectElement_ = Blockly.createSvgElement('rect',
{'height': this.height_ + 'px',
'width': this.width_ + 'px',
'fill-opacity': 0}, this.fieldGroup_);
}
block.getSvgRoot().appendChild(this.fieldGroup_);
// Configure the field to be transparent with respect to tooltips.
var topElement = this.rectElement_ || this.imageElement_;
topElement.tooltip = this.sourceBlock_;
Blockly.Tooltip.bindMouseEvents(topElement);
if(this.clickEventListener){
this.imageElement_.addEventListener("click", callingClick);
}
};
在此之后,您必須添加myFieldImage而不是使用fieldImage。 和isClickListener參數將從該塊傳遞。 以下是代碼-
Blockly.Blocks['MyBlock'] = {
init: function() {
this.appendDummyInput()
.appendField(new MyFieldImage("https://www.gstatic.com/codesite/ph/images/star_on.gif", 15, 15, "*",true));
this.setTooltip('');
this.setHelpUrl('http://www.example.com/');
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.