Creating complex buttons without using images(DOM) (Phaser3)

This article can be read in about 3 minutes.
PR

The purpose 

In Phaser 3, you can register click events to GameObjects and use them as buttons.

However, with GameObjects, it is difficult to create complex buttons other than using images with simple shapes like rectangles or circles.

Here, we will create sophisticated buttons using DOM objects.

PR

Creation

The creation of DOM objects was introduced in the following article.

Based on the article, I created the following function.

export function createBtn(scene, x, y, text, font_size, color, callback){
    let el = document.createElement('div');
    el.innerHTML = text
    el.onclick =callback;
    let style = "font: ' + font_size + 'px Arial;color:' + color + ';border-color:' + color + ';border:solid; ";// you should add button style
    let btn = scene.add.dom(x, y, el, style); 

    return btn;
}

The style variable sets the button’s style.

I’ve added border-radius and user-select in addition.

In particular, it’s better to set user-select to none, because otherwise, the text within the button can be selected by dragging.

Call

The above function is called from within the Scene class like this:

let x = 100;
let y = 200;
let html = "BUT<i>TON</i>"
let font_size = 10;
let color  =  "#000000" ;
let func = () =>{alert()};
createRadiusBtn(this, x, y, html ,font_size , color ,func )

The html variable can include other tags like in the example. You can also insert line breaks using <br> etc.

PR

Result

I was able to create elaborate buttons without using images.

The text displayed is ”BUT<i>TON</i>”.

comment

Copied title and URL