,代码如下:

// 获取 canvas 元素
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

// 定义 RedButton 类
function RedButton(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

// 绘制 RedButton
RedButton.prototype.draw = function() {
  ctx.fillStyle = 'red';
  ctx.fillRect(this.x, this.y, this.width, this.height);
}

// 添加 RedButton 的点击事件
RedButton.prototype.onClick = function(e) {
  if (e.offsetX >= this.x && e.offsetX <= this.x + this.width &&
      e.offsetY >= this.y && e.offsetY <= this.y + this.height) {
    console.log('RedButton clicked!');
  }
}

// 定义 GreenButton 类
function GreenButton(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

// 绘制 GreenButton
GreenButton.prototype.draw = function() {
  ctx.fillStyle = 'green';
  ctx.fillRect(this.x, this.y, this.width, this.height);
}

// 添加 GreenButton 的点击事件
GreenButton.prototype.onClick = function(e) {
  if (e.offsetX >= this.x && e.offsetX <= this.x + this.width &&
      e.offsetY >= this.y && e.offsetY <= this.y + this.height) {
    console.log('GreenButton clicked!');
  }
}

// 创建 RedButton 和 GreenButton 对象
var redButton = new RedButton(50, 50, 100, 50);
var greenButton = new GreenButton(200, 50, 100, 50);

// 绘制按钮
redButton.draw();
greenButton.draw();

// 添加点击事件监听器
canvas.addEventListener('click', function(e) {
  redButton.onClick(e);
  greenButton.onClick(e);
});

以上代码中,我们先分别定义了 RedButton 和 GreenButton 类,这两个类都有 x、y、width 和 height 属性,分别表示按钮的左上角坐标和宽高。然后,我们给这两个类分别添加了 draw 和 onClick 方法。draw 方法用于绘制按钮,onClick 方法用于处理按钮的点击事件。

在创建 RedButton 和 GreenButton 对象后,我们调用它们的 draw 方法,绘制按钮。然后,我们给 canvas 元素添加一个点击事件监听器,当用户点击 canvas 时,依次调用 RedButton 和 GreenButton 对象的 onClick 方法,判断用户是否点击了按钮区域,如果是,则输出相应的提示信息

在 Canvas 中创建两个按钮对象命名为 RedButton 和 GreenButton

原文地址: https://www.cveoy.top/t/topic/cRA4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录