How can I use an SVG element created with JSX as an image source in a Canvas?

南笙酒味 提交于 2021-02-08 10:10:40

问题


I have a ReactJS application. I'm dynamically generating SVG images as JSX components. So far, so good -- but now I need to use the SVG as an image source in a Canvas element. This works fine with static SVG files, but how can I get the dynamic SVG into the canvas?

A simplified version appears in the snippet. Two approaches to the drawImage call are shown in the componentDidMount method: creating an unmounted SvgSource, and using a ref to one mounted on the page, but they both fail.

class App extends React.Component {

	// On mount, paint the SVG in the canvas
	componentDidMount(){
  	let ctx = this.canvasRef.getContext("2d")
    
    // THIS DOES NOT WORK:
  	//ctx.drawImage(new SvgSource({fill: "green"}), 50, 50);
    
    // NOR DOES THIS:
    //ctx.drawImage(this.svgRef, 50, 50);
    
    /* TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, SVGImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap. */
  }

  render() {
  return (
  <div>     
    {/* This works, inserting the SvgSource element directly - but that's not what I want. */}
    <SvgSource ref={s => this.svgRef = s} fill="blue" />
    
    {/* I want to use the SVG as an image source in this canvas. */}
  	<canvas 
      ref={
      c => this.canvasRef = c 
      /* NB: using older ref syntax because jsFiddle uses React .14 - use CreateRef with version 16 */
      } 
      width={200} 
      height={200} />
  </div>
  );
  }
}

// Our JSX SVG component that provides the custom image to use in the canvas
class SvgSource extends React.Component {
  render() {
    return (
      <svg width={100} height={100} viewBox="0 0 100 100">
        <circle cx={50} cy={50} r={25} fill={this.props.fill || "red"}/>
      </svg>
    );
  }
}

ReactDOM.render(<App />, document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  min-height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

To clarify: I know how to insert ordinary SVG images into canvas elements. The problem is converting a JSX SVG into a valid source for a drawImage on the canvas context, so that this can all be done in React components.


回答1:


This is not a very graceful way to do it, but it's what I ended up with:

class SvgSource extends React.Component {
    generateSvg() {
        return "data:image/svg+xml;base64," + 
            btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="25" fill="${this.props.fill}" /></svg>`);
    }

    render() {
        return (<img src={this.generateSvg()} />);
    }
}

Instead of making the SVG a JSX object, I just construct it as a string, encoding to base64 for use as a data URL. I can then return an <img> JSX element from the render() function to use the image directly in the page. When I need to use it in a canvas, I can call new SvgSource({fill: "green"}).generateSvg() directly, using the returned string in a plain (non-JSX) <img> element's src attribute.

I could find no better way to get the SVG markup rendered without actually putting it on the page.



来源:https://stackoverflow.com/questions/54748928/how-can-i-use-an-svg-element-created-with-jsx-as-an-image-source-in-a-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!