Dvingo.GitHub.io


SVG Blending

2015-07-21 05:00:00 +0000

Playing around with blending two SVG images through a canvas element. One design constraint was to have the SVG be inline in order to do dynamic color changing before applying the blending (and to support resizing). This makes use of the SVGInjector library.

The code is:

function importSVG(sourceSVG, targetCanvas) {
  var svgXml = (new XMLSerializer()).serializeToString(sourceSVG)
  var ctx = targetCanvas.getContext('2d')
  ctx.globalCompositeOperation = 'multiply'
  var img = new Image()
  img.height = '400'
  img.width = '400'
  img.onload = function() {
    ctx.drawImage(img, 0, 0, 400, 400)
  }
  img.src = "data:image/svg+xml;base64," + btoa(svgXml)
}

var options = {
  evalScripts:'never',
  each: function(svg) {
    svg.style.height = '400px'
    svg.style.width = '400px'
    importSVG(svg, document.querySelector('canvas'))
  }
}

SVGInjector(document.querySelectorAll('.replace'), options)