简体   繁体   English

使用javascript动态更改背景图像

[英]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; 我正在使用javascript和canvas元素来创建背景,我将其存储在一个数组中,以便用户可以在它们之间切换; the images are jpegs 图像是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: 但是,我注意到操纵背景的javascript如下:

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? 有没有办法强制document.body.style.backgroundImage接受动态创建的图像而不是仅仅从域中加载一个?

toDataURL will give you a data url which can be used in place of a regular url. toDataURL将为您提供一个数据网址,可用于代替常规网址。 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 只需用你从toDataURL获取的url替换url,在本例中为someimage.jpg

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. 另请注意,在使用数据URL之前,无需将数据URL加载到图像对象中。 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+')';

You can use the result of toDataURL like a real URL. 您可以像使用真实URL一样使用toDataURL的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM