Martin Martin - 2 years ago 207
Javascript Question

Unable to preload and display SVG with CreateJS

I am trying to preload a set of SVG objects and display them using CreateJS/PreloadJS. So far I was able to display a SVG object without preloading, but as soon as I use the LoadQueue from PreloadJS, I can't get my sample to work.

Does somebody know what I am doing wrong here? Thanks!


var imageManifest = [
{ id: "MySvgImage", src: "" }

var stage = new createjs.Stage(document.getElementById('gameCanvas'));

var assetQueue = new createjs.LoadQueue(true);
assetQueue.on('complete', complete);

function complete(e) {
var svgImage = new createjs.Bitmap(assetQueue.getResult('MySvgImage'));

var svgImage2 = new createjs.Bitmap("");


function tick() {


<!DOCTYPE html>

<html lang="en">
<script src=""></script>
<script src=""></script>
<script src="app.js"></script>
<canvas id="gameCanvas" width="800" height="800"></canvas>

Answer Source

There are a few issues with your sample, which prevent the preloading of the asset, but unfortunately if those are addressed, it still will not draw into the Canvas.

Getting Preloading to work: The asset will need to be hosted on a server with CORS enabled to do cross-domain loading. PreloadJS will use XHR to load SVG, which can not load cross-domain without some extra work. The updated sample below shows that in action.

// Note: Requires very latest PreloadJS (NEXT in GitHub)
var assetQueue = new createjs.LoadQueue(true, null, true);
// 3rd parameter is "crossOrigin", and requires a CORS server.

Once preloaded, the asset can be appended to the DOM, but not used as a source for an EaselJS Bitmap. It appears that Canvas can not use drawImage with a local SVG source. It CAN be appended to the DOM thought.

The reason your second approach did work was that it was automatically treating the source of the Bitmap as an image path, so it loaded it as an image (Bitmap creates an image behind the scenes when it is passed a string path)

It is probably a good idea to add image-based preloading to PreloadJS - I will add an issue to the GitHub.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download