Dynamically change background image using javascript

I am looking for an opportunity to change the background of a webpage to a dynamically generated image at runtime. I use javascript and a canvas element to create a background that I store in an array so that the user can switch between them; jpegs images

// canvas computations snipped

var img = c.toDataURL("image/jpeg");
this.modifiedanimationarray[0] = new Image();
this.modifiedanimationarray[0].src = img; 

However, I noticed that javascript for controlling the background looks like this:

document.body.style.backgroundImage = "url('whatever.jpg')";

he wants to get an image from a URL that is not dynamically created. Is there a way to force document.body.style.backgroundImage to accept an image created on the fly, and not just load it from a domain?

+4
source share
2

toDataURL URL- , URL-. ,

document.body.style.backgroundImage = 'url(someimage.jpg)';

url, someimage.jpg, URL-, toDataURL

document.body.style.backgroundImage = 'url('+canvas.toDataURL("image/jpeg")+')';

function getBG(){
  var canvas = document.getElementById('bgcanvas'),
      context = canvas.getContext('2d'),
      cX = canvas.width / 2,
      cY = canvas.height / 2;
      context.beginPath();
      context.arc(cX, cY, 70, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
      context.stroke();
  return canvas.toDataURL("image/jpeg");
}

document.body.style.backgroundImage = 'url('+getBG()+')';
canvas {
  display:none;
}
<canvas id="bgcanvas" width="200" height="200"></canvas>
Hide result

, URL- . , :

var img = c.toDataURL("image/jpeg");
this.modifiedanimationarray[0] = new Image();
this.modifiedanimationarray[0].src = img; 

var img = c.toDataURL("image/jpeg");
this.modifiedanimationarray[0] = img;
document.body.style.backgroundImage = 'url('+this.modifiedanimationarray[0]+')';
//or just
document.body.style.backgroundImage = 'url('+img+')';
+4

toDataURL URL.

var img = c.toDataURL("image/jpeg");
document.body.style.backgroundImage = "url(" + img + ")";
+1

Source: https://habr.com/ru/post/1627074/


All Articles