Search code examples
javascriptreactjscanvg

how to add text in canvas with react and canvg library?


i'm trying to add text in canvas ( bottom right ) with react and canvg lib

This is what i try :

DownloadImage = (i) => {
        var _this = this;
        this.modeler.saveSVG(function (err, svg) {
            if (err) console.log(err)
            _this.setState({ datasvg: svg }, function () {
                const canvas = _this.refs.canvasforimage;
                console.log(canvas)

                const options = {
                    log: false,
                    ignoreMouse: true
                };

                canvg(canvas, this.state.datasvg, options);
                    const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                    const element = document.createElement("a");
                    element.setAttribute('download', 'diagram.png');
                    element.setAttribute('href', image);
                    element.click();
            })
        })
    }


    render = () => {
        return (
                <canvas  ref="canvasforimage" id="canvasforimage">
                 {/* <div style="position:absolute;right:0;bottom:0">Text</div> */} Not working
                </canvas>
        )

function above is working... i can download as image but code at render the one i commented not working


Solution

  • thanks for the comment @Chris G so i already solve the problem by adding code after canvg

    canvg(canvas, this.state.datasvg, options);
    const ctx = canvas.getContext('2d');
    ctx.fillText('Hello world',50, 50);