You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

104 lines
3.0 KiB

import { Text, Graphics, Container, TextStyle, NineSlicePlane, Texture } from "pixi.js";
interface IOpts {
text: string;
bg: string;
pressBg: string;
position: null | any;
click(): void;
}
const defaultOpts: IOpts = {
text: "",
bg: "",
position: null,
pressBg: "",
click() { },
};
function getConfig() {
return Object.assign({}, defaultOpts)
}
export default function Button(opts: Partial<IOpts>) {
let curOpts: IOpts = getConfig();
; (Object.keys(defaultOpts) as (keyof IOpts)[]).forEach((key) => {
if (opts[key] != undefined) {
curOpts[key] = opts[key] as any;
}
});
let textStyle = new TextStyle({
fontFamily: "Arial",
fontSize: 30,
fill: 0xffffff,
align: "center",
});
let textStr = new Text(curOpts.text, textStyle);
let xPadding = 60;
let yPadding = 40;
let button = new Container();
let width = textStr.width + xPadding;
let height = textStr.height + yPadding;
// https://www.cnblogs.com/ningmin/p/11412170.html
// https://blog.csdn.net/weixin_52919504/article/details/131854745
// https://blog.csdn.net/weixin_52919504/article/details/131854745
button.pivot.set(width / 2, height / 2)
textStr.x = xPadding / 2;
textStr.y = yPadding / 2 - 2;
if (!curOpts.bg) {
const rect = new Graphics();
rect.name = "rect";
rect.beginFill(0xff0000);
rect.drawRect(0, 0, width, height);
rect.endFill();
rect.interactive = true;
rect.buttonMode = true;
button.addChild(rect);
} else {
const plane9 = new NineSlicePlane(Texture.from(curOpts.bg), 10, 10, 10, 10);
plane9.name = "nine-pic"
plane9.width = width
plane9.height = height
plane9.interactive = true;
plane9.buttonMode = true;
button.addChild(plane9);
}
button.addChild(textStr);
button.interactive = true;
if(curOpts.position) {
button.position = curOpts.position
}
button.on("touchstart", () => {
if (curOpts.pressBg) {
button.getChildByName<NineSlicePlane>("nine-pic").texture = Texture.from(curOpts.pressBg)
} else {
button.alpha = 0.8;
button.scale = { x: .8, y: .8 }
}
});
button.on("touchend", () => {
// 点击成功
console.log("touchend success");
if (curOpts.pressBg) {
button.getChildByName<NineSlicePlane>("nine-pic").texture = Texture.from(curOpts.bg)
} else {
button.alpha = 1;
button.scale = { x: 1, y: 1 }
}
curOpts.click();
});
button.on("touchendoutside", () => {
console.log("touchendoutside success");
if (curOpts.pressBg) {
button.getChildByName<NineSlicePlane>("nine-pic").texture = Texture.from(curOpts.bg)
} else {
button.alpha = 1;
button.scale = { x: 1, y: 1 }
}
});
return button;
}