关于canvas的getContext()方法的一个奇怪的问题,哪位大侠来帮帮忙

eric1031 2013-01-18 10:50:45
用js的面向对象的方式给对象两个属性canvas和ctx,分别表示画布和画布上下文,在draw函数中调用的时候为什么canvas属性返回的是type是object,而ctx属性返回的是undefined,按理说ctx应该也是一个object啊,哪位大侠可以帮忙看看。

<!DOCTYPE html>
<html>
<head>
<title>test code</title>
<script type="text/javascript">
function GameObjectManager(){
this.canvas = document.getElementById("canvas");
this.ctx = this.canvas.getContext("2d");
};

GameObjectManager.prototype.draw = function(){
alert(typeof(this.canvas));
alert(typeof(this.ctx));
};

GameObjectManager.prototype.run = function(){
setInterval(this.draw, 60);
};

window.onload = init;

function init(){
var gameObjectManager = new GameObjectManager();
gameObjectManager.run();
}

</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>
...全文
1683 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2013-01-18
  • 打赏
  • 举报
回复
解决办法:

 GameObjectManager.prototype.run = function(){
			var _this = this;
            setInterval(function(){
				_this.draw();
			}, 60);
        };
「已注销」 2013-01-18
  • 打赏
  • 举报
回复
因为你那个this是指向window对象的

87,991

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧