SVG to Html5 Canvas issue Failed to execute 'drawImage' on 'CanvasRenderingContext2D'

Viewed 143

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

I am trying to load svg inline element to html5 canvas( convert svg to image and then load img to canvas). Seem getting error while drawImage from CanvasRenderingContext2D.drawImage.

I tried to use HTML2Canvas library but it seem not working in ie11(image not rendered in canvas)


import React from "react";

export default class SVGToCanvas extends React.Component {
    constructor(props) {
        super(props);
        this.state = { dataUrl: null };
    }

    handlePrint = (ele) => {
        const svg = new XMLSerializer().serializeToString(this.mysvg);
        let imgData = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
        this.myimg.src = imgData;
    }

    imgLoad = (img) => {
        debugger;
        this.mycanvas.width = 100;
        this.mycanvas.height = 100;

        const canvas = document.getElementById('mycanvas');
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0); // getting error 
   }

    render() {
        return (
            <div id="mydiv">
                <button onClick={this.handlePrint}>Print</button>
                <div >
                    <svg ref={ref => this.mysvg = ref} id="mysvg" width="100" height="100">
                        <circle cx="50" cy="50" r="40" stroke="green" strokeWidth="4" fill="yellow" />
                    </svg>
                </div>
                <canvas id="mycanvas" ref={ref => this.mycanvas = ref}></canvas>
                <img ref={ref => this.myimg = ref} src={this.state.dataUrl} onLoad={this.imgLoad} alt="" id="myimg" />
            </div>

        )
    }
}
0 Answers
Related