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.
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>