html - Dynamically change background image using javascript -
i'm looking being able change background of webpage dynamically generated image @ runtime. i'm using javascript , canvas element create backgrounds, i'm storing in array user can toggle between them; images jpegs
// canvas computations snipped var img = c.todataurl("image/jpeg"); this.modifiedanimationarray[0] = new image(); this.modifiedanimationarray[0].src = img;
however, have noticed javascript manipulate background follows:
document.body.style.backgroundimage = "url('whatever.jpg')";
it wants image url, created non-dynamically. there way force document.body.style.backgroundimage accept image created on-the-fly rather loading 1 off domain?
todataurl give data url can used in place of regular url. instead of doing say
document.body.style.backgroundimage = 'url(someimage.jpg)';
just replace url, in case someimage.jpg
, url got 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 not need load data url image object before using it. meaning not need do:
var img = c.todataurl("image/jpeg"); this.modifiedanimationarray[0] = new image(); this.modifiedanimationarray[0].src = img;
you do
var img = c.todataurl("image/jpeg"); this.modifiedanimationarray[0] = img; document.body.style.backgroundimage = 'url('+this.modifiedanimationarray[0]+')'; //or document.body.style.backgroundimage = 'url('+img+')';
Comments
Post a Comment