JAVASCRIPT - 无法读取undefined的属性'show'

时间:2018-04-23 16:36:22

标签: javascript

我的代码有错误帮助我!

我制作了一个代码来创建一个屏幕然后显示圆圈,但代码却给出了错误。有人可以帮我解决这个错误吗?

var blob;
var blobs = [];
var x;
var y;

window.onload = function(){
	c 		  = document.createElement('canvas');
	width	  = 300;
	height	  = 300;
	c.width   = width;
	c.height  = height;
	ctx		  = c.getContext('2d');
	document.body.appendChild(c);

	setInterval(draw(), 1000/30)

	blob = new Blob(width/2, height/2, 64);
}

function draw(){
	ctx.rect(0, 0, width, height);
	ctx.fillstyle = 'black';
	ctx.fill();

	blob.show();
}

function Blob(x, y, r){
	this.pos = this.x, this.y = x, y;
	this.r = r;

	this.show = function(){
		ctx.fillstyle = 'white';
		ctx.fill();
		ctx.ellipse(this.pos.x, this.pos.y, this.r*2, this.r*2);
	}
}
<!DOCTYPE html>
<html>
	<head>
		<script></script>
	</head>
	<body>
		
	</body>
</html>

这是错误:无法读取未定义的属性'show'

1 个答案:

答案 0 :(得分:4)

您正在调用该方法而不是传递对函数的引用

setInterval(draw(), 1000/30) //here the blob instance is still not created thus the error

将其更改为:

setInterval(draw, 1000/30)