찾다
웹 프론트엔드CSS 튜토리얼CSS3를 사용하여 불규칙한 이미지에 대한 전환 효과를 만드는 방법

CSS3을 사용하여 불규칙한 이미지에 대한 전환 효과를 만드는 방법에 대한 소스 코드를 가져오세요. 필요한 친구가 사용할 수 있습니다.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TweenMax不规则图片切换特效</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="container"> </div>
<script src=&#39;js/delaunay.js&#39;></script>
<script src=&#39;js/TweenMax.js&#39;></script>
<script>
 
const TWO_PI = Math.PI * 2;
 
var images = [],
    imageIndex = 0;
 
var image,
    imageWidth = 768,
    imageHeight = 485;
 
var vertices = [],
    indices = [],
    prevfrag = [],
    fragments = [];
 
var margin = 50;
 
var container = document.getElementById(&#39;container&#39;);
 
var clickPosition = [imageWidth * 0.5, imageHeight * 0.5];
 
window.onload = function() {
    TweenMax.set(container, {perspective:500});
 
    // images from http://www.hdwallpapers.in
    var urls = [
            &#39;images/1.jpg&#39;,
            &#39;images/2.jpg&#39;,
            &#39;images/3.jpg&#39;,
            &#39;images/4.jpg&#39;
        ],
        image,
        loaded = 0;
    // very quick and dirty hack to load and display the first image asap
    images[0] = image = new Image();
        image.onload = function() {
            if (++loaded === 1) {
               
                for (var i = 1; i < 4; i++) {
                    images[i] = image = new Image();
 
                    image.src = urls[i];
                }
                placeImage();
            }
        };
        image.src = urls[0];
};
 
function placeImage(transitionIn) {
    image = images[imageIndex];
 
    if (++imageIndex === images.length) imageIndex = 0;
 
    var num = Math.random();
    if(num < .25) {
      image.direction = "left";
    } else if(num < .5) {
      image.direction = "top";
    } else if(num < .75) {
      image.direction = "bottom";
    } else {
      image.direction = "right";
    }
 
    container.appendChild(image);
    image.style.opacity = 0;
 
    if (transitionIn !== false) {
        triangulateIn();
    }
}
 
function triangulateIn(event) {
    var box = image.getBoundingClientRect(),
        top = box.top,
        left = box.left;
 
    if(image.direction == "left") {
      clickPosition[0] = 0;
      clickPosition[1] = imageHeight / 2;
    } else if(image.direction == "top") {
      clickPosition[0] = imageWidth / 2;
      clickPosition[1] = 0;
    } else if(image.direction == "bottom") {
      clickPosition[0] = imageWidth / 2;
      clickPosition[1] = imageHeight;
    } else if(image.direction == "right") {
      clickPosition[0] = imageWidth;
      clickPosition[1] = imageHeight / 2;
    }
   
 
    triangulate();
    build();
}
 
function triangulate() {
    for(var i = 0; i < 40; i++) {     
      x = -margin + Math.random() * (imageWidth + margin * 2);
      y = -margin + Math.random() * (imageHeight + margin * 2);
      vertices.push([x, y]);
    }
    vertices.push([0,0]);
    vertices.push([imageWidth,0]);
    vertices.push([imageWidth, imageHeight]);
    vertices.push([0, imageHeight]);
 
    vertices.forEach(function(v) {
        v[0] = clamp(v[0], 0, imageWidth);
        v[1] = clamp(v[1], 0, imageHeight);
    });
 
    indices = Delaunay.triangulate(vertices);
}
 
function build() {
    var p0, p1, p2,
        fragment;
 
    var tl0 = new TimelineMax({onComplete:buildCompleteHandler});
 
    for (var i = 0; i < indices.length; i += 3) {
        p0 = vertices[indices[i + 0]];
        p1 = vertices[indices[i + 1]];
        p2 = vertices[indices[i + 2]];
 
        fragment = new Fragment(p0, p1, p2);
 
        var dx = fragment.centroid[0] - clickPosition[0],
            dy = fragment.centroid[1] - clickPosition[1],
            d = Math.sqrt(dx * dx + dy * dy),
            rx = 30 * sign(dy),
            ry = 90 * -sign(dx),
            delay = d * 0.003 * randomRange(0.9, 1.1);
        fragment.canvas.style.zIndex = Math.floor(d).toString();
 
        var tl1 = new TimelineMax();
 
        if(image.direction == "left") {
          rx = Math.abs(rx);
          ry = 0;         
        } else if(image.direction == "top") {
          rx = 0;
          ry = Math.abs(ry);
        } else if(image.direction == "bottom") {
          rx = 0;
          ry = - Math.abs(ry);
        } else if(image.direction == "right") {
          rx = - Math.abs(rx);
          ry = 0;
        }
       
        tl1.from(fragment.canvas, 1, {
              z:-50,
              rotationX:rx,
              rotationY:ry,
              scaleX:0,
              scaleY:0,
              ease:Cubic.easeIn
         });
        tl1.from(fragment.canvas, 0.4,{alpha:0}, 0.6);
     
        tl0.insert(tl1, delay);
 
        fragments.push(fragment);
        container.appendChild(fragment.canvas);
    }
}
 
function buildCompleteHandler() {
    // add pooling?
    image.style.opacity = 1;
    image.addEventListener(&#39;transitionend&#39;, function catchTrans() {
      fragments.forEach(function(f) {
          container.removeChild(f.canvas);
      });
 
      fragments.length = 0;
      vertices.length = 0;
      indices.length = 0;
 
      placeImage();
      this.removeEventListener(&#39;transitionend&#39;,catchTrans,false);
    }, false);
   
}
 
//////////////
// MATH UTILS
//////////////
 
function randomRange(min, max) {
    return min + (max - min) * Math.random();
}
 
function clamp(x, min, max) {
    return x < min ? min : (x > max ? max : x);
}
 
function sign(x) {
    return x < 0 ? -1 : 1;
}
 
//////////////
// FRAGMENT
//////////////
 
Fragment = function(v0, v1, v2) {
    this.v0 = v0;
    this.v1 = v1;
    this.v2 = v2;
 
    this.computeBoundingBox();
    this.computeCentroid();
    this.createCanvas();
    this.clip();
};
Fragment.prototype = {
    computeBoundingBox:function() {
        var xMin = Math.min(this.v0[0], this.v1[0], this.v2[0]),
            xMax = Math.max(this.v0[0], this.v1[0], this.v2[0]),
            yMin = Math.min(this.v0[1], this.v1[1], this.v2[1]),
            yMax = Math.max(this.v0[1], this.v1[1], this.v2[1]);
 
         this.box = {
            x:Math.round(xMin),
            y:Math.round(yMin),
            w:Math.round(xMax - xMin),
            h:Math.round(yMax - yMin)
        };
 
    },
    computeCentroid:function() {
        var x = (this.v0[0] + this.v1[0] + this.v2[0]) / 3,
            y = (this.v0[1] + this.v1[1] + this.v2[1]) / 3;
 
        this.centroid = [x, y];
    },
    createCanvas:function() {
        this.canvas = document.createElement(&#39;canvas&#39;);
        this.canvas.width = this.box.w;
        this.canvas.height = this.box.h;
        this.canvas.style.width = this.box.w + &#39;px&#39;;
        this.canvas.style.height = this.box.h + &#39;px&#39;;
        this.canvas.style.left = this.box.x + &#39;px&#39;;
        this.canvas.style.top = this.box.y + &#39;px&#39;;
        this.ctx = this.canvas.getContext(&#39;2d&#39;);
    },
    clip:function() {
        this.ctx.save();
        this.ctx.translate(-this.box.x, -this.box.y);
        this.ctx.beginPath();
        this.ctx.moveTo(this.v0[0], this.v0[1]);
        this.ctx.lineTo(this.v1[0], this.v1[1]);
        this.ctx.lineTo(this.v2[0], this.v2[1]);
        this.ctx.closePath();
        this.ctx.clip();
        this.ctx.drawImage(image, 0, 0);
        this.ctx.restore();
    }
};//@ sourceURL=pen.js
</script>
 
<div style="text-align:center;margin:10px 0; font:normal 14px/24px &#39;MicroSoft YaHei&#39;;">
</div>
</body>
</html>

불규칙한 이미지의 전환 특수 효과를 생성하는 코드는 여기까지입니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

관련 읽기:

CSS3 미디어 쿼리를 사용하는 방법

HTML의 웹 표준은 무엇입니까

CSS3을 사용하여 반응형 레이아웃을 만드는 방법

위 내용은 CSS3를 사용하여 불규칙한 이미지에 대한 전환 효과를 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
css怎么隐藏元素但不占空间css怎么隐藏元素但不占空间Jun 01, 2022 pm 07:15 PM

两种方法:1、利用display属性,只需给元素添加“display:none;”样式即可。2、利用position和top属性设置元素绝对定位来隐藏元素,只需给元素添加“position:absolute;top:-9999px;”样式。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

css3什么是自适应布局css3什么是自适应布局Jun 02, 2022 pm 12:05 PM

自适应布局又称“响应式布局”,是指可以自动识别屏幕宽度、并做出相应调整的网页布局;这样的网页能够兼容多个不同的终端,而不是为每个终端做一个特定的版本。自适应布局是为解决移动端浏览网页而诞生的,能够为使用不同终端的用户提供很好的用户体验。

css3如何实现鼠标点击图片放大css3如何实现鼠标点击图片放大Apr 25, 2022 pm 04:52 PM

实现方法:1、使用“:active”选择器选中鼠标点击图片的状态;2、使用transform属性和scale()函数实现图片放大效果,语法“img:active {transform: scale(x轴放大倍数,y轴放大倍数);}”。

css3动画效果有变形吗css3动画效果有变形吗Apr 28, 2022 pm 02:20 PM

css3中的动画效果有变形;可以利用“animation:动画属性 @keyframes ..{..{transform:变形属性}}”实现变形动画效果,animation属性用于设置动画样式,transform属性用于设置变形样式。

css3怎么设置动画旋转速度css3怎么设置动画旋转速度Apr 28, 2022 pm 04:32 PM

在css3中,可以利用“animation-timing-function”属性设置动画旋转速度,该属性用于指定动画将如何完成一个周期,设置动画的速度曲线,语法为“元素{animation-timing-function:速度属性值;}”。

一文了解CSS3中的新特性 ::target-text 选择器一文了解CSS3中的新特性 ::target-text 选择器Apr 12, 2022 am 11:24 AM

本篇文章带大家一起深入了解一下CSS3中的新特性::target-text 选择器,聊聊该选择器的作用和使用方法,希望对大家有所帮助!

css3线性渐变可以实现三角形吗css3线性渐变可以实现三角形吗Apr 25, 2022 pm 02:47 PM

css3线性渐变可以实现三角形;只需创建一个45度的线性渐变,设置渐变色为两种固定颜色,一个是三角形的颜色,另一个为透明色即可,语法“linear-gradient(45deg,颜色值,颜色值 50%,透明色 50%,透明色 100%)”。

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.