Game Development Reference
In-Depth Information
That's really all there is to it. The code that makes up all the other windows is the
same for all of them. In fact, we only open a bunch of windows pointing to the exact
same script. As far as each window is concerned, they are the only window opened.
All they do is take a bunch of data through the messaging API, then render that data
if the shouldDraw flag is set. Otherwise, they just clear their canvas, and sit tight
waiting for further instructions from their parent window.
// 1. Create a canvas
var canvas = document.createElement("canvas");
canvas.width = 400;
canvas.height = 300;
// 2. Attach the canvas to the DOM
document.body.appendChild(canvas);
// 3. Get a reference to the canvas' context
var ctx = canvas.getContext("2d");
// 4. Set up the callback to receive messages
from some parent window
function doOnMessage(event) {
// 5. For security, make sure we only process
input from a trusted window
if (event.origin == "http://localhost") {
var data = event.data;
ctx.clearRect(0, 0, canvas.width,
canvas.height);
// 6. And here's where the magic happens
for this window. If told to
// draw something through the message
received, go ahead and do so.
if (data.shouldDraw) {
ctx.fillStyle = data.color;
ctx.fillRect(data.x, data.y, data.w,
data.h);
}
}
}
window.addEventListener("message", doOnMessage,
false);
Search WWH ::




Custom Search