Reputation: 5952
I have an HTML document that looks like this:
<!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>
and here's 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);
}
}
Now, the first part - the "context.fillStyle = " and the "context.fillRect()" - work fine. It shows up as a red rectangle in my browser (using Firefox on a Mac btw).
But when I try to create a sky object and then pass the context to render it, nothing happens. I can't figure out why it won't execute the render function on the sky object.
Am I misunderstanding how JS objects work?
Here is the (very simple) CSS, in case someone wants to try running it all.
/* landscape.css */
#landscape{
border: 2px solid black;
}
Upvotes: 0
Views: 1964
Reputation: 46903
That's because your render function is private
, in that it's only accessible from inside your sky()
function.
In order for it to work, you need to provide external accessibility (by adding a property to this
)
Try
this.render = function(thecontext) {
}
Upvotes: 4