目前,我正在使用画布通过 javascript 动态生成灰度图像。灰度代码如下:
// Grayscale w canvas method
function grayscale(src)
{
var canvasUrl = false;
try
{
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
canvasUrl = canvas.toDataURL();
}
catch(err)
{
canvasUrl = false;
}
return canvasUrl;
}
在我的代码中,我的图像放置在div
. 在 javascript 执行并完成生成所有图像的灰度表示之前,它div
具有设置“display:none”,此时它将设置div
为具有“display:block”。
这在大多数情况下都有效,但并非所有时候都有效。 有时,div
不会显示,因为以下行发生错误:
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
基于关于 SO 的相关问题,一般的解决方案似乎是用于$(window).load(func);
运行灰度生成代码。
但是,这就是我正在做的事情:
<script type="text/javascript">
var animateTime = 250;
// On window load. This waits until images have loaded which is essential
$(window).load(function(){
// Fade in images so there isn't a color "pop" document load and then on window load
$(".item img").animate({opacity:1},animateTime);
// clone image
$('.item img').each(function(){
var el = $(this);
el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
var el = $(this);
el.parent().css({"width":el.css("width"),"height":el.css("height")});
el.dequeue();
});
this.src = grayscale(this.src);
if(!this.src)
alert('An error occurred.'); // handle the occasional DOM error...
});
// Fade image
$('.item img').mouseover(function(){
$(this).parent().find('img:first').stop().animate({opacity:1}, animateTime);
})
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, animateTime);
});
$('.item').mouseover(function() {
$(this).children('h3').css('display', 'block');
$(this).children('h3').stop().animate({opacity:1}, animateTime);
});
$('.item').mouseout(function() {
$(this).children('h3').css('display', 'none');
$(this).children('h3').stop();
$(this).children('h3').css('opacity', '0');
});
$("#loading").css('display', 'none'); // hide the loading GIF
$(".outer_content_container").css('display', 'block');
$(".outer_content_container").animate({opacity:1}, animateTime*4);
});
</script>
这让我想到:我设置“显示:无”的事实是否可以?在包含图像的父div
级上导致浏览器根本不加载图像并继续调用window.onload?