如何在单击组件时调用函数

How to call a function on a click on a component?

本文关键字:调用 函数 组件 单击      更新时间:2023-09-26
function component(width, height, source, x, y) {
    this.image = new Image();
    this.image.src = source;
    this.width = width;
    this.height = height;  
    this.x = x;
    this.y = y;    
    this.update = function() {
        ctx = myGameArea.context;
        ctx.drawImage(this.image, 
            this.x, 
            this.y,
            this.width, this.height);
    }
    this.newPos = function(a, b, image, h) {
        this.x = a;
        this.y = b;
        this.image.src = image;
        this.height = h;
    }
}

单击组件后如何调用函数?还是我应该只记录单击的坐标并将它们与组件的坐标进行比较?

在使用HTML5 Canvas时,不幸的是,没有单独的节点可以注册点击事件。您唯一真正的选择是在<canvas>元素本身上注册一个单击事件,然后使用 X 和 Y 坐标来确定单击的组件。

我不知道

您使用的是香草JS还是特殊引擎,但是如果您可以使用JQuery,也许您必须查看此 https://api.jquery.com/click/,它允许您每次单击组件时执行一个函数下面的代码只是一个关于如何使用该函数的示例,请对其进行测试以确保它适合您

    function component(width, height, source, x, y) {
    this.image = new Image();
    this.image.src = source;
    this.width = width;
    this.height = height;  
    this.x = x;
    this.y = y;    
    this.update = function() {
        ctx = myGameArea.context;
        ctx.drawImage(this.image, 
            this.x, 
            this.y,
            this.width, this.height);
    }
    this.newPos = function(a, b, image, h) {
        this.x = a;
        this.y = b;
        this.image.src = image;
        this.height = h;
    }
    $(this).click(function(){
        //Code here
    });
}