我的要求——
- 随机图像显示在 div/canvas 内
- 图像高度应调整为父高度
- 图像宽度应按比例调整大小(与高度)
- 如果图像宽度大于父宽度,则从左右均匀裁剪
我已经用java脚本实现了这一点。Jsfiddle 位于http://jsfiddle.net/yesprasoon/N3WvF/。您可以调整输出窗口的大小以查看它是如何工作的。
但是我觉得我这样做很乏味,并且在 CSS 和/或 jQuery 中有一些非常简单的东西。你能帮我处理纯 CSS(最好)吗?
我在这里也附上了java脚本 -
var strDataURI;
//
displayBackground(true);
//
window.onresize = function(event) {
displayBackground(false);
}
//
function displayBackground(bChangeImage)
{
//alert("displayBackground");
var appWidth = window.innerWidth;
var appHeight = window.innerHeight;
//
if (bChangeImage)
{
var suffix_array = ["_california","_easter","_eiffel","_hk","_taj"];
var ran = Math.floor((Math.random()*5)+1);
ran = ran - 1;
//ran = 3;
strDataURI = "http://minds-eye.info/TP_Test/TP"+suffix_array[ran]+".jpg";
}
//
var myCanvas = document.getElementById('canvas');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.canvas.width = appWidth;
ctx.canvas.height = appHeight;
//
var hFraction = appHeight / img.naturalHeight;
var displayWidth = img.naturalWidth*hFraction;
mrgLeft = (appWidth - displayWidth)/2;
mrgTop = (appHeight - img.naturalHeight)/2;
ctx.drawImage(img,mrgLeft,0, displayWidth, appHeight);
//blurMargin = 20;
//stackBlurCanvasRGB( "canvas", blurMargin, blurMargin, appWidth-blurMargin*2, appHeight-blurMargin*2, 6 );
};
img.src = strDataURI;
}