javascript “this” keyword not referring to correct thing

前端 未结 3 1833
余生分开走
余生分开走 2021-01-23 12:05
var ball = {
    x: 20,
    y: 500,
    vx: 100,
    vy: 100,
    width: 13,
    height: 13,
    draw: function() { 
        var img = new Image();  
        img.src = \         


        
3条回答
  •  自闭症患者
    2021-01-23 12:31

    Yes, basically you need to use a closure. All you need to do is refer to the variables by their parent instead of by the use of this, which will actually refer to the img element in the function. So just change your code to

    ctx.drawImage(img, ball.x, ball.y);  
    

    or even

    ctx.drawImage(this, ball.x, ball.y);  
    

提交回复
热议问题