Html5中Canvas玩一玩

本文介绍了如何使用JavaScript创建一个可交互的按钮组件,包括设置类型、文本和前景颜色,并展示了在不同浏览器上的测试效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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上测试通过。

效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值