Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change background image using javascript

I'm looking into being able to change the background of a webpage to a dynamically generated image at runtime. I'm using javascript and the canvas element to create the backgrounds, which I'm storing in an array so that the user can toggle between them; the images are jpegs

// canvas computations snipped

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

However, I have noticed that the javascript to manipulate the background is as follows:

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

it wants an image from a url, that is created non-dynamically. Is there any way to force the document.body.style.backgroundImage to accept an image created on-the-fly rather than just loading one off a domain?

like image 270
EventHorizon Avatar asked Feb 02 '16 23:02

EventHorizon


2 Answers

toDataURL will give you a data url which can be used in place of a regular url. So instead of doing say

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

just replace the url, in this case someimage.jpg, with the url you got from toDataURL

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

Demo

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>

Also note you do not need to load a data url into an image object before using it. Meaning you do not need to do:

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

You would just do

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+')';
like image 53
Patrick Evans Avatar answered Oct 06 '22 03:10

Patrick Evans


You can use the result of toDataURL like a real URL.

var img = c.toDataURL("image/jpeg");
document.body.style.backgroundImage = "url(" + img + ")";
like image 36
NineBerry Avatar answered Oct 06 '22 02:10

NineBerry