js代码
function Button() {
var canvas = document.createElement("canvas");
Object.defineProperty(canvas, "type", {
get: function () {
return this._type_;
},
set: function (value) {
if (this._type_ == undefined) {
this._type_ = value;
RedrawButton(this);
}
}
});
Object.defineProperty(canvas, "text", {
get: function () {
return this._text_;
},
set: function (value) {
this._text_ = value;
RedrawButton(this);
}
});
Object.defineProperty(canvas, "foreground", {
get: function () {
return this._foreground_;
},
set: function (value) {
this._foreground_ = value;
RedrawButton(this);
}
});
canvas.type = "button";
canvas.width = 70;
canvas.height = 30;
canvas.foreground = "#000000";
return canvas;
}
function RedrawButton(canvas) {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#EEEEF2";// 背景色
ctx.fillRect(0, 0, canvas.width, canvas.height);// 背景
ctx.strokeRect(0, 0, canvas.width, canvas.height);// 边框
ctx.textAlign = "center";// 设置居中
ctx.fillStyle = canvas._foreground_;
ctx.fillText(canvas._text_, canvas.width / 2, canvas.height / 2);// 绘制文字
}
页面测试代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="JavaScript1.js"></script>
<script type="text/javascript">
function TEST() {
var d = document.getElementById("d");
var b = new Button();
b.text = "123";
b.text = "456";
d.appendChild(b);
}
</script>
</head>
<body onload="TEST();">
<div id="d"></div>
</body>
</html>
在谷歌浏览器、firefox、IE11上测试通过。
效果图: