gpt4 book ai didi

javascript - 为多个图像添加 HTML5 Canvas 黑白效果

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:59 26 4
gpt4 key购买 nike

我想使用 HTML5 Canvas Black 创建一个画廊来实现悬停效果,但是我遇到了一些麻烦。

我可以让效果在一个元素上完美运行,但我似乎无法让它在多个元素上运行。

这是我的:

(function() {  
var supportsCanvas = !!document.createElement('canvas').getContext;
supportsCanvas && (window.onload = greyImages);

function greyImages() {
var ctx = document.getElementsByTagName("canvas")[0].getContext('2d'),
img = document.getElementById("cvs-src"),
imageData, px, length, i = 0,
grey;

ctx.drawImage(img, 0, 0);

// Set 500,500 to the width and height of your image.
imageData = ctx.getImageData(0, 0, 378, 225);
px = imageData.data;
length = px.length;

for ( ; i < length; i+= 4 ) {
grey = px[i] * .1 + px[i+1] * .1 + px[i+2] * .1;
px[i] = px[i+1] = px[i+2] = grey;
}

ctx.putImageData(imageData, 0, 0);
}
})();

HTML:

<article id="respond" class="first">
<a href="gitano.php" rel="#overlay" style="text-decoration:none">
<img id="cvs-src" src="images/thumbnails/regular/gitano.png" />
<canvas width=378 height=225></canvas>
<div class="caption">
<p><img class="enlarge" src="images/enlarge.png"/>Click To <em>View Project</em></p>
</div>
</a>
</article>

CSS:

   figure article img {
width: 100%;
padding: 0;
margin: 0;
border: 0;
vertical-align:bottom;
}

figure article:hover img {
display: block;
}

figure article canvas {
width: 100%;
padding: 0;
margin: 0;
border: 0;
position: absolute;
left: 0;
top: 0;
opacity: 1;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 1s;
}

figure article canvas:hover {
opacity: 0;
}

最佳答案

看起来你只将它应用到这里的一个 Canvas 上:

var ctx = document.getElementsByTagName("canvas")[0].getContext('2d')

您正在获取第一个 Canvas ([0]) 并获取其上下文。也许这样会更好:

var canvases = document.getElementsByTagName("canvas");
for (var j = 0; j < canvases.length; j ++) {
var ctx = canvases[j].getContext('2d'),
img = document.getElementById("cvs-src"),
imageData, px, length, i = 0,
grey;
// and so on...
}

关于javascript - 为多个图像添加 HTML5 Canvas 黑白效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8020950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com