จุดประสงค์ของตัวอย่างนี้คือการแสดงวิธีสร้างเอฟเฟกต์การระงับเมาส์ของภาพสีเทา/สีโดยใช้ HTML5 และ jQuery ก่อนที่ HTML5 จะปรากฏขึ้นการบรรลุเอฟเฟกต์นี้ต้องใช้สองภาพสองรุ่นสีและสีเทา ตอนนี้ HTML5 ทำให้การสร้างเอฟเฟกต์นี้ง่ายขึ้นและมีประสิทธิภาพมากขึ้นเนื่องจากภาพสีเทาจะถูกสร้างขึ้นโดยตรงจากไฟล์ต้นฉบับ ฉันหวังว่าคุณจะพบว่าสคริปต์นี้มีประโยชน์ในการออกแบบเช่นตู้แสดงผลหรืออัลบั้มรูปภาพ
รหัส jQuery ต่อไปนี้จะค้นหาภาพเป้าหมายและสร้างเวอร์ชันสีเทา เมื่อเมาส์ถูกระงับบนภาพรหัสจะค่อยๆเปลี่ยนภาพสีเทาเป็นสี
- <mce: scriptsrc = jQuery.min.jsmce_src = jQuery.min.jstype = text/javascript> </mce: script>
- <mce: scriptType = text/javascript> <!-
- //onwindowload.ThiswaitsuntilimagesHaveLoaded ซึ่งเป็นสิ่งสำคัญ
- $ (หน้าต่าง) .load (function () {
- // fadeinimagessothereis notacolorpopdocumentload และ onwindowload
- $ (. itemimg) .fadein (500);
- // cloneimage
- $ ('. itemimg'). แต่ละ (ฟังก์ชั่น () {
- varel = $ (นี่);
- el.css ({ตำแหน่ง: สัมบูรณ์}). wrap (<divclass = 'img_wrapper'style = แสดง: inline-blockmce_style = แสดง: inline-block>) clone (). addclass ('img_grayscale'). css ({ตำแหน่ง: สัมบูรณ์, z-index: 998, ความทึบ: 0})
- varel = $ (นี่);
- El.Parent (). CSS ({width: this.width, ความสูง: this.height});
- El.Dequeue ();
- -
- this.src = grayscale (this.src);
- -
- // fadeimage
- $ ('. itemimg'). mouseover (function () {
- $ (นี่) .parent (). find ('img: first'). stop (). animate ({opacity: 1}, 1,000);
- -
- $ ('. img_grayscale'). mouseout (function () {
- $ (นี่) .stop (). animate ({ความทึบ: 0}, 1000);
- -
- -
- // grayscalewcanvasmethod
- FunctionGrayScale (SRC) {
- varcanvas = document.createElement ('Canvas');
- varctx = canvas.getContext ('2d');
- varimGobj = newImage ();
- imgobj.src = src;
- canvas.width = imgobj.width;
- canvas.height = imgobj.height;
- ctx.drawimage (imgobj, 0,0);
- varimgPixels = ctx.getimagedata (0,0, canvas.width, canvas.height);
- สำหรับ (vary = 0; y <imgpixels.height; y ++) {
- สำหรับ (varx = 0; x <imgpixels.width; x ++) {
- vari = (y*4)*imgpixels.width+x*4;
- varavg = (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);
- returncanvas.todataurl ();
- -
- //-> </mce: สคริปต์>
วิธีใช้ * อ้างถึง jQuery.js
* วางรหัสข้างต้น
* ตั้งค่าภาพเป้าหมาย (ตัวอย่างเช่น. post-img, img, .gallery img ฯลฯ )
* คุณสามารถเปลี่ยนความเร็วของภาพเคลื่อนไหว (ตัวอย่างเช่น 1,000 = 1 วินาที)
ความเข้ากันได้ สามารถทำงานกับเบราว์เซอร์ใด ๆ ที่รองรับ HTML5 และ JavaScript เช่น Chrome, Safari และ Firefox หากเบราว์เซอร์ไม่รองรับ HTML5 เอฟเฟกต์นี้จะกลับไปเป็นภาพสีดั้งเดิม หมายเหตุ: หากไฟล์ท้องถิ่นไม่ทำงานบน Firefox และ Chrome คุณต้องใส่รหัส HTML บนเว็บเซิร์ฟเวอร์