title: Data URIs causing syntax errors in Javascript
body: <p>I'm trying to draw an image inside a canvas element using a data URI. I'm using Django and passing a variable containing the base64 encoding of the photo to the template. In the past, I have used that like so:</p>
  <pre><code>&lt;img src=&quot;data:image/jpg;base64, {{ photo_data }}&quot;&gt;
  </code></pre>
  <p>This works fine. I now want to replace that with this:</p>
  <pre><code>&lt;canvas id=&quot;canvas&quot;&gt;&lt;/canvas&gt;
  </code></pre>
  <p>and use javascript to draw the image in the canvas. I tried out the code from <a href="https://stackoverflow.com/a/4776378/1763621">this answer</a>:</p>
  <pre><code>var canvas = $('#canvas');
  var ctx = canvas.getContext('2d');
  var img = new Image;
  $(img).load(function(){
      ctx.drawImage(img, 0, 0);
  });
  img.src = &quot;data:image/jpg;base64, {{ photo_data }}&quot;
  </code></pre>
  <p>This gives me the javascript error &quot;SyntaxError: unterminated string literal&quot; on the last line. I read that this error usually happens because of line breaks. Upon inspecting the page source it looks like there are line breaks in there:</p>
  <p><img src="https://i.stack.imgur.com/iGHlh.png" alt="enter image description here" /></p>
  <p>So then I tried removing line breaks:</p>
  <pre><code>function removeBreaks(data){
      return data.replace(/(\r\n|\n|\r)/gm, &quot;&quot;);
  }
  
  var photo_data = removeBreaks({{ photo_data }});
  </code></pre>
  <p>Now I'm getting a new error when I call removeBreaks. &quot;SyntaxError: identifier starts immediately after numeric literal&quot;.</p>
  <pre><code>var photo_data = removeBreaks(/9j/4AAQSkZ...
  ----------------------------------^
  </code></pre>
  <p>Is there some sort of escaping I need to do, and if so how would I do it?</p>
  <p><em><strong>Update</strong></em></p>
  <p>I tried all of the suggestions from the comments and the answer. So far the thing that has come closest to working is doing</p>
  <pre><code>photo_data = json.dumps(&lt;base64 encoded image file&gt;)
  </code></pre>
  <p>on the Django side and</p>
  <pre><code>var photo_data = &quot;{{ photo_data }}&quot;.replace(/&amp;quot;/g,&quot;&quot;);
  img.src = &quot;data:image/jpg;base64, &quot; + photo_data;
  </code></pre>
  <p>on the Javascript side. The image doesn't show at all if I don't replace the <code>&amp;quot;</code>s, and when I do remove them only the top third of the image shows. I tried resizing the canvas element, that doesn't seem to be the issue.</p>
  <p><em><strong>Update #2</strong></em></p>
  <p>Turns out the canvas size was the issue. Width and height of the canvas element need to be as big or bigger than the width and height of the image, which I wasn't setting when I created the <code>Image</code> object. Both the accepted answer and json.dumps (with the <code>&amp;quot;</code> caveat) work to solve the original problem.</p>