2

After line with canvas.toDataURL() I get an error with

Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvas may no be exported

Tried to search solution at my own, with cross origin, but this didn't help me. Is there any possibility to download image created on canvas? I saw examples with toDataURL(), but those unfortunately don't work for me. I will consider other solutions.

   _handleSaveButton(){
    var canvas = document.getElementById('memesCanvas');
    console.log(canvas);
    
    var canvasimage=document.createElement("img");
    canvasimage.setAttribute('crossOrigin','anonymous');
    canvasimage = canvas.toDataURL('image/png');
    canvasimage.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
    alert(canvasimage);
  }
 
 <ReactButton onClick={() => this._handleSaveButton()} styleName={'generate-meme'} name='generate meme'/>
Observer
  • 3,506
  • 1
  • 16
  • 32
kozi
  • 105
  • 1
  • 11
  • canvasimage.crossOrigin = '*'; doesn't help too – kozi Nov 08 '17 at 20:34
  • Have you tried the other solutions mentioned in the accepted answer [here](https://stackoverflow.com/questions/22710627/tainted-canvases-may-not-be-exported)? – T Porter Nov 08 '17 at 21:05
  • Are you using [`drawImage()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage) anywhere? How are you loading the image that you are providing to `drawImage()`? Is it over the `file://` protocol? Is the image on a different domain? – zero298 Nov 08 '17 at 21:36

1 Answers1

2

I did this for a code challenge not too long ago. Not sure if this is exactly what you need but I hope it helps.

import React, { Component } from "react";

class Save extends Component{
  saveCanvas() {
    const canvasSave = document.getElementById('resetCanvas');
    const d = canvasSave.toDataURL('image/png');
    const w = window.open('about:blank', 'image from canvas');
    w.document.write("<img src='"+d+"' alt='from canvas'/>");
    console.log('Saved!');
  }

  render(){
    return(
      <div>
        <button onClick={ this.saveCanvas }>Save</button>
      </div>
    )
  }
}

export default Save;
OsuDani
  • 88
  • 1
  • 11
  • thanks for help, btw i dont know why but just window.open return error - with 'about:blank' - no error at all :) – kozi Nov 08 '17 at 22:07
  • Glad I could help! :) – OsuDani Nov 09 '17 at 13:29
  • 1
    You should under no circumstances manipulate the DOM. Please refer to this link https://stackoverflow.com/questions/41435734/should-i-manipulate-dom-directly-or-using-react-state-props – Safwat Fathi Feb 08 '21 at 12:27