ReactJS add Iframe inside Canvas context

Viewed 20

I have a ReactJS code like this

let context = canvas.getContext('2d');
let renderSize = (video1ScaleMode === 'fill') ? fillSize(video1Size, canvasSize, 1) : fitSize(video1Size, canvasSize, 1);
let xOffset = (canvasSize.width - renderSize.width) / 2;
let yOffset = (canvasSize.height - renderSize.height) / 2;
context.drawImage(video1, xOffset, yOffset, renderSize.width, renderSize.height);

This loads the camera inside the canvas. This is working fine.

I want to add a webpage (with animations) behind the camera view. For that I tried to add IFrame (because the URL is from the server)

For that I tried the following code

iframe.js

import React, { Component } from 'react'
import { createPortal } from 'react-dom'

export class IFrame extends Component {
constructor(props) {
    super(props)
    this.state = {
        mountNode: null
    }
    this.setContentRef = (contentRef) => {
        this.setState({
            mountNode: contentRef?.contentWindow?.document?.body
        })
    }
}

render() {
    const { children, ...props } = this.props
    const { mountNode } = this.state
    return (
        <iframe
            {...props}
            ref={this.setContentRef}
        >
            {mountNode && createPortal(children, mountNode)}
        </iframe>
    )
}
}

My usage is like this

import { IFrame } from './iframe'

const MyComp = () => (
 <IFrame>
    https://www.helloworld.com
 </IFrame>
)
context.drawImage(MyComp, xOffset, yOffset, renderSize.width, renderSize.height);

For that I got error like this

**

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'. at renderFrame

**

I understand that IFrame component is not like HTMLCanvasElement or ImageElement or VideoElement.

I would like to know how I can add the IFrame or some other way to bring image from URL as background of Video.

1 Answers

You could visually position your iframe behind the canvas using css. Perhaps like this:

<div class="container">
  <canvas></canvas>
  <iframe></iframe>
</div>
.container {
  position: relative;
}

iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}
Related