<div id="app"></div>
body {
  font-family: Trebuchet MS, sans-serif;
}
.download-link {
  color: black;
  text-decoration: none;
  background: white;
  padding: 1rem;
  border-radius: 5px;
  margin: 1rem;
  font-size: 2rem;
  box-shadow: 0 6px 6px rgba(0,0,0,.4)
}

.download {
  display: flex;
  flex-wrap: wrap;
  position: absolute;
  bottom: 2rem;
  left: 2rem;
}
import SvgTile from 'https://codepen.io/pehaa/pen/b32a3ca026500dca4dbcd29fc1d53f1a.js'
const tartan = [
  { fill: "#FF8A00", size: 40 },
  { fill: "#E52E71", size: 10 },
  { fill: "#FFFFFF", size: 10 },
  { fill: "#E52E71", size: 70 },
  { fill: "#100e17", size: 20 },
  { fill: "#E52E71", size: 70 },
  { fill: "#FFFFFF", size: 10 },
  { fill: "#E52E71", size: 10 },
  { fill: "#FF8A00", size: 40 },
]

const SvgBg = ({ svgData }) => {
  return (
    <div
        style={{
          width: "100%",
          height: "100vh",
          backgroundImage: `url("data:image/svg+xml;utf8,${svgData}")`,
        }}
      />
  )
}

const SvgDownloadLink = ({ svgData, fileName="file" }) => {
  return (
    <a
      className="download-link"
      download={`${fileName}.svg`}
      href={`data:image/svg+xml;utf8,${svgData}`}
    >
      Download as SVG
    </a>
  )
}


const PngDownloadLink = ({ svgData, width, height, fileName="file" }) => {
  
  const aEl = React.createRef()

  React.useEffect(() => {
    const canvas = document.createElement("canvas")
    canvas.width = 2 * width
    canvas.height = 2 * height
    const ctx = canvas.getContext("2d")
    ctx.scale(2, 2)
    let img = new Image()
    img.src = `data:image/svg+xml, ${svgData}`
    img.onload = () => {
      ctx.drawImage(img, 0, 0)
      const href = canvas.toDataURL("image/png")
      aEl.current.setAttribute("href", href)
    }
  }, [])

  return (
    <a 
      className="download-link"
      ref={aEl} 
      download={`${fileName}.png`}
    >
      Download as PNG
    </a>
  )
}


const App = () => {
  const Tile = SvgTile({tartan})
  const tartanSize = Tile.props.width
  const tartanStr = ReactDOMServer.renderToStaticMarkup( <SvgTile tartan={tartan}/>)
  const tartanData = encodeURIComponent(tartanStr)
  return (
    <div className="App">
      <SvgBg svgData={tartanData} />
      <div className="download">
        <PngDownloadLink svgData={tartanData} fileName="CssTricks" width={tartanSize} height={tartanSize}/>
        <SvgDownloadLink svgData={tartanData} fileName="CssTricks" />
      </div>
    </div>
  )
}

const rootElement = document.getElementById("app")
ReactDOM.render(<App />, rootElement)
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js
  3. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom-server.browser.production.min.js