面向对象编程起步——神来之笔

本文介绍了一个简单的面向对象编程示例,通过定义棋子类(Piece)和棋盘类(Checkerboard),展示了如何使用JavaScript实现基本的对象交互。文章中包含了构造方法、绘图操作等关键代码实现。

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

面向对象编程思想

class Piece {
    /* 棋子类 */
    constructor(canvas) {
        /* 构造方法 */
        this.cs = canvas; /* 绑定画布 */
        this.pRadius = 20; /* 规定棋子半径 */
    }
    log() {
        console.log(this.pRadius);
    }
}
class Checkerboard {
    /* 棋盘类 */
    constructor(canvas,style) {
        this.cs = canvas;
        this.length = 50; /* 规定方格长度 */
        this.se=style;
    }
    draw() {
        let width = parseInt(this.se.width);
        let height = parseInt(this.se.height);
        // let height = parseInt(this.cs.style.height);
        this.cs.clearRect(0, 0, width, height);
        this.cs.save();
        this.cs.fillStyle='rgb(174, 107, 45)'
        this.cs.fillRect(0, 0, width, height);
        console.log(width, height);
        this.cs.restore();
        for (let i = 0; i < 12; i++) {
            for (let j = 0; j < 12; j++) {
                this.cs.strokeRect(i * this.length, j * this.length, (i + 1) * this.length, (j + 1) * this.length)
                if (i == 3 && j == 3||i==9&&j==3||i==3&&j==9||i==9&&j==9||i==6&&j==6) {
                    this.cs.beginPath();
                    this.cs.arc(i * this.length, j * this.length, 3, 0, 2 * Math.PI, false);
                    this.cs.fill();
                }
            }
        }
        
    }
}
document.ready = init; /* JS程序起点 */
function init() {
    /* 获取画布对象 */
    let c1 = document.getElementById('c1');
    let c1_style=window.getComputedStyle(c1,null);
    if (c1.getContext) {
        c1 = c1.getContext('2d');
    }
    /* 棋盘实例 */
    let cb1 = new Checkerboard(c1,c1_style);
    cb1.draw();
    /* 棋子实例 */
    let p1 = new Piece(c1);
    p1.log();

}

@沉木

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值