Pixi.JS - How to Render SVG on iOS Safari

Published by Hendry Sadrak
Posted on ,
Updated on

I found a tedious bug for Safari (which by 10 July 2018 is still not fixed) when preloading svgs for a game I was developing. Issue was that all svgs that were loaded, were drawn over last one, like the canvas wasn't cleared. I debugged pixi.js and tried to create some workaround but no solution. The solution I found was that we had to load the svgs by ourselves and just feed pixi the texture.

The solution:

const pixelRatio = window.devicePixelRatio || 1

const svgLoader = (resource, next) => {
  if (resource.extension !== 'svg') return next()

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const image = new Image()

  const onImageLoad = () => {
    canvas.width = image.width *= pixelRatio
    canvas.height = image.height *= pixelRatio

    ctx.drawImage(image, 0, 0, image.width, image.height)

    resource.texture = PIXI.Texture.fromCanvas(canvas)


  image.addEventListener('load', onImageLoad)
  image.crossOrigin = 'anonymous'
  image.src = resource.url

Add it to PIXI.loader as pre middleware before loading anything.


It's simple as that!

I posted the original solution at https://github.com/pixijs/pixijs/issues/3949#issuecomment-392732546.