当我点击屏幕上的图像时,如何更改画布中的精灵

时间:2015-05-16 03:26:52

标签: javascript html5 canvas

我目前正在制作基于画布的基本游戏,目前我的角色精灵设置为目录中的特定图像。在画布的外面,我有一些其他图像(也保存在目录中),我希望能够点击将精灵更改为点击的图像。

我试过玩一些onclick功能,但没有取得任何成功。我试着玩弄

<c:forEach var="parent1" items="${model.list}"> <form:checkbox path="list" value="${parent1.name}" label="${parent1.name}" /> </for:each>

将其更改为

var Player = function(){ this.sprite = 'images/char-boy.png'; this.x = 300; this.y = 550; }

这就是html的样子

var Player = function(){
    this.sprite = function char_select(){
        var toon = document.getElementById(this);
        return toon;
    };
    this.x = 300;
    this.y = 550;
}

我从未使用过jsfiddle,但我复制并粘贴了我真正快速的东西并想出了这个。 https://jsfiddle.net/tibbs/u2pztuxj/

1 个答案:

答案 0 :(得分:0)

您的图片的onclick属性无效,因为您的代码有误 - 函数名称为sprite,而不是char_select。它还需要是Player

实例的一部分

试试这个:(现在你不需要图像上的onclick属性)

var myPlayer;

//Define Player object
var Player = function() {
    this.sprite = 'path/to/image.png';        
    this.char_select = function(clicked_img) {
        //Set sprite to clicked_img's src attribute
        this.sprite = clicked_img.src;
    };
    this.x = 300;
    this.y = 550;
}      

window.onload = function() {
    //Create a new player instance
    myPlayer = new Player();

    //Add click listener for the image(s)
    document.getElementById('boy').addEventListener('click', function() {
        //Call the char_select function with the clicked image as an parameter
        myPlayer.char_select(this);
    });

    //Add more event listeners as required...
}
相关问题