@cortez.connelly
To create a canvas element inside an iframe, you can follow these steps:
- 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>
|
- 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>
|
- 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>
|
- Save and run the HTML file with the JavaScript code to see the canvas element created inside the iframe displaying a blue rectangle.