我有一个HTML文档,如下所示:
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet"
type = "text/css"
href = "landscape.css" />
</head>
<body>
<h1 id = "heading">My Landscape</h1>
<canvas id = "landscape" width = "800" height = "600">
landscape
</canvas>
<script type = "text/javascript"
src = "landscape.js">
</script>
</body>
</html>
这里是landscape.js:
var canvas = document.getElementById('landscape');
var context = canvas.getContext('2d');
context.fillStyle = "#ff0000";
context.fillRect(20, 20, 150, 100);
var mySky = new sky(40, 40);
mySky.render(context);
function sky(x, y){
this.x = x;
this.y = y;
function render(theContext){
theContext.fillStyle = "#00ff00";
theContext.fillRect(x, y, 150, 100);
}
}
现在,第一部分 - “context.fillStyle =”和“context.fillRect()” - 工作正常。它在我的浏览器中显示为红色矩形(在Mac btw上使用Firefox)。
但是当我尝试创建一个天空对象然后传递上下文来渲染它时,没有任何反应。我无法弄清楚为什么它不会在天空物体上执行渲染功能。
我是否误解了JS对象的工作原理?
这是(非常简单的)CSS,以防有人想尝试运行它。
/* landscape.css */
#landscape{
border: 2px solid black;
}
答案 0 :(得分:4)
这是因为你的渲染函数是private
,因为它只能从sky()
函数内部访问。
为了使其正常工作,您需要提供外部辅助功能(通过向this
添加属性)
尝试
this.render = function(thecontext) {
}