1

I'm looking to set the background of a canvas with an image created with JavaScript rather than with a simple URL.

<script>
      var v = document.getElementById("video1");
      var canvas1 = document.getElementById("firstcanvas");
      var ctx1 = canvas1.getContext("2d");
      var canvas2 = document.getElementById("secondCanvas");
      var ctx2 = canvas2.getContext("2d");

      var i;
      function draw() {
        ctx1.drawImage(v, 0, 0, 300, 150);
        transform();
      }
      function transform() {
        var dataURL = canvas1.toDataURL("image/png");

        canvas2.style.backgroundImage = dataURL;

      }
      v.addEventListener("play", function() {i = window.setInterval("draw()", 200);}, false);
      v.addEventListener("pause", function() {window.clearInterval(i);}, false);
      v.addEventListener("ended", function() {window.clearInterval(i);}, false);
      </script>

Simply put, this code: 1. Continually draws a frame from a video to a canvas using drawImage after which 2. The canvas is converted to an ACTUAL image using dataURL, 3. The image is to be set as the BACKGROUND for the final canvas. The final part, as you might have guessed, doesn't work. I just a working code to set a background image without a URL preferably with the format I presented. Thank you.

1 Answer 1

1

You can't just simply assign the data returned by .toDataURL() to the backgroundImage property as it expects it to be wrapped inside "url()".

Here's an example:

var canvas1 = document.getElementById("firstCanvas");
var ctx1 = canvas1.getContext("2d");
var canvas2 = document.getElementById("secondCanvas");
var ctx2 = canvas2.getContext("2d");

ctx1.beginPath();
ctx1.arc(50, 50, 40, 0, 2 * Math.PI);
ctx1.stroke();

function transform() {
  var dataURL = canvas1.toDataURL("image/png");
  canvas2.style.backgroundImage = "url(" + dataURL + ")";
}
transform();
<canvas id="firstCanvas" width="100" height="100"></canvas>
<canvas id="secondCanvas" width="100" height="100"></canvas>

Sign up to request clarification or add additional context in comments.

4 Comments

Not related to question, but im still curious: do you know how to provide a link to a blob instead of inline base64? I mean createObjectURL. And will it work with canvas. Thanks in advance
Sry for bothering you, was so curious that tested myself) Here it is - jsfiddle.net/aqj7c382. Hella shorter
Obscure thanks so much. It’s been bugging me and I knew it was something basic that just didn’t know. Works fine, thanks again
No problem Zodiax - glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.