0

I have a javascript file that is being called by 2 html files, I need the javascript to edit the canvas that is on 1.html and 2.html, this doesn't work unless I put both canvasses in the same html file. Is there a way to work around this problem, here is the code:

HTML1

        <body>
    <canvas class="canvas" id="canvas1"></canvas>
        </body
    </html>

HTML2

        <!DOCTYPE html>
    <html>
        <head>
     <script type="text/javascript" src="script.js"></script>
        </head>

        <body>
    <canvas class="canvas" id="canvas2"></canvas>
        </body
    </html>

Javascript:

    for (var i = 1; i<3; i++) {         
var c=document.getElementById("canvas"+[i]);        
var ctx=c.getContext("2d"); 
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
}

This doesn't work unless I put both canvasses in the same html file, then it works

EDIT: Please note that I do want the code to be running in the background at all times, updating the htlm files I'm not in. The filling and clearing is just a placeholder for my code, which is not part of the problem

1
  • canvas1 doesn't exist in HTML2 and canvas2 doesn't exist in HTML1. You need to check before using the canvas. Commented Dec 16, 2013 at 10:03

2 Answers 2

2

Short answer: No there isn't.

Long answer:

JavaScript is always scoped to the current document, so you can't access 2 at the same time. However, there are ways to do this if both documents are in some kind of hierarchy.

If you open a new window from 1.html you can save a reference to that new window and access it's content. JavaScriptKit: Accessing objects of window via another

This also works vice versa via the window.opener reference.

New in HTML5 is also window.postMessage. You might want to look into this as it might serve your need. Mozilla Developer Network:window.postMessage

If you plainly want the same script to work on 2 pages, simply use the same id for both canvasses and not a loop and you should be fine.

var c=document.getElementById("canvas");        
var ctx=c.getContext("2d"); 
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);

And your html:

<!--1.html-->
…
<canvas class="canvas" id="canvas"></canvas>
…

<!--2.html-->
…
<canvas class="canvas" id="canvas"></canvas>
…
Sign up to request clarification or add additional context in comments.

Comments

0

If you getElementById for an element that doesn't exist, you will get undefined.

If you try to access a property of undefined, you will get an error and the script will stop executing.

After getting the element, test to see if you got an element, and skip to the next loop iteration if you did not.

if (typeof ctx === "undefined") { continue; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.