2017-05-04 70 views
1

你好我无法理解在哪里和哪里不能使用p5.js方法。在这种codepen在对象内部使用p5.js宽度和高度方法的问题

var bubble = { 
    x: 200, 
    y: 200, 
    display: function() { 
    stroke(255); 
    strokeWeight(4); 
    noFill(); 
    ellipse(this.x, this.y, 24, 24); 
    }, 
    move: function() { 
    this.x = this.x + random(-1, 1); 
    this.y = this.y + random(-1, 1); 
    } 
} 

function setup() { 
    createCanvas(600, 400); 

} 

function draw() { 
    background(0); 
    bubble.display(); 
    bubble.move(); 
    ellipse(width/2,height/2,50,50) 
} 

如果我替换x和y值与我的“泡沫”对象内部,例如,“宽度/ 2”和“高度/ 2” - 控制台打印“宽度”没有被定义?如果我在draw()函数内使用相同的方法,它可以正常工作。我猜这是一个范围界定问题?但不知道如何解决它。非常感谢。

回答

1
var bubble = { 
    init : function(){ 
    this.x = width/2; 
    this.y = height/2; 
    }, 
    display: function() { 
    stroke(255); 
    strokeWeight(4); 
    noFill(); 
    ellipse(this.x, this.y, 24, 24); 
    }, 
    move: function() { 
    this.x = mouseX; 
    this.y = mouseY; 
    } 
} 

我不能告诉你为什么它不工作,我不出来,但这里是一个可行的解决方案

+0

感谢您的时间 – James

+0

这个工作,因为匿名的情况下函数在p5实例的显示和设置方法中的范围是正确的,而普通对象的范围是全局窗口。 p5作者通过支持这样的全局方法使这变得复杂。 – Bosworth99