当我在JQuery中按空格键时,如何在HTML画布上创建图像?

70gysomp  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(129)

我想创建一个图像时,空格键被按下,以模拟子弹发射。问题是,当我在JQuery中调用一个draw image函数时,在函数外部声明了图像及其路径,图像根本不会出现在屏幕上。我怎样才能使它,使子弹是创建时,空格键被按下,并继续下去,直到它离开屏幕?

var bullet = new Image();
bullet.src = "Resources/bullet.png"

$(document).keydown(function(event) {  //jQuery code to recognize a keydown event
    var keycode = (event.keyCode ? event.keyCode : event.which);

    if (keycode === 32) {
        //gun facing left
        if (facingleft === true) {

^^^ Don't know how to draw the image when the key is pressed ^^^

            collideFunction()
        }
    }

});

字符串

thtygnil

thtygnil1#

这可能会起作用:

//create a function that allows you to move the bullet with spacebar and 
giving the bullet a direction

    function move(element) {
       element.style.position = 'fixed'

       function moveToCoordinates(left, bottom) {
           element.style.left = left + 'px'
           element.style.bottom = bottom + 'px'
       }

        function moveWithSpaceBar(left, bottom, callback){
            let direction = null;
            let x = left;
            let y = bottom;

            element.style.left = x + 'px'
            element.style.bottom = y + 'px'

            function shootBullet(){
                if(direction === 'east'){
                    x+=1
                }
            }

            setInterval(shootBullet, 1)

            // create event listener for spacebar

            document.addEventListener('keydown', function(e){
                if(e.key === " "){
                    direction = 'east'
                }
                callback(direction)
            })
            document.addEventListener('keyup', function(e){
                direction = null
                callback(direction)
            })
        }
        
        return {
            to: moveToCoordinates
            withSpaceBar: moveWithSpaceBar
        }
    }



   //now create your bullet and allow the image to change then move when 
   called 

    function bulletShot(x, y){
        const element = newImage('starting img, perhaps its blank')
        // give it a z index if needed
        element.style.zIndex = 1;

        function bulletDirection(direction){
            if (direction === null){
            element.src = `starting img, perhaps its blank`
            }

            if (direction === 'east'){
            element.src = `bullet img intended to move, perhaps a gif`
            }
        } 

        move(element).withSpaceBar(x, y, bulletDirection)
        return{
            element: element
        }
    }

字符串
我不知道这是否能解决你的问题,但也许有人会发现它有帮助。这是我在训练营中学习如何移动/更改图像的一种方法。我不是一个专业的开发人员,我实际上对JS很陌生。因此,这可能适用于或不适用于您的具体情况。我很高兴看到有人纠正我的代码。祝你们今天愉快。

相关问题