How to create a canvas element inside an iframe?

by cortez.connelly , in category: HTML & CSS , 3 months ago

How to create a canvas element inside an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 3 months ago

@cortez.connelly 

To create a canvas element inside an iframe, you can follow these steps:

  1. Create an HTML file with an iframe element:
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
    <title>IFrame Example</title>
</head>
<body>
    <iframe id="myFrame" src="canvas.html"></iframe>
</body>
</html>


  1. Create another HTML file with a canvas element inside it (canvas.html):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
    <title>Canvas Example</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
        canvas {
            display: block;
            margin: auto;
            background-color: lightgray;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>


  1. Add JavaScript code to access the canvas element inside the iframe:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
    <title>Canvas Example</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
        canvas {
            display: block;
            margin: auto;
            background-color: lightgray;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>

    <script>
        const iframe = document.getElementById('myFrame');
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        const canvas = iframeDoc.getElementById('myCanvas');
        
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = 'blue';
        ctx.fillRect(50, 50, 100, 100);
    </script>
</body>
</html>


  1. Save and run the HTML file with the JavaScript code to see the canvas element created inside the iframe displaying a blue rectangle.