我想创建一个视差滚动网站的三张图片,但只有两个卷轴工作

I want to create a parallax scrolling website of three pictures but only two scrolls work

本文关键字:两个 工作 一个 创建 视差 滚动 网站 三张      更新时间:2023-09-26

我正在尝试使用javascript和html/css创建平行滚动效果。滚动必须适用于三张图片,所以第一张和第二张图片平行滚动,但我不能让第二张和第三张也这样做我是一个javascript的新手,我正在学习通过做

CSS

#img1{
    width: 100%;
    height: 970px;
    position: relative;
    z-index: -1;
}
#img2{
    width: 100%;
    height: 970px;
    position: relative;
    z-index: 1;
}
#img3{
    width: 100%;
    height: 970px;
    position: relative;
    z-index: 1;
}

JS

var ypos,image,image2;
function parallex() {
    ypos = pageYOffset;
    image = document.getElementById('img1');
    image.style.top= ypos* .8 +'px';
}
function parallex2() {
    ypos = pageYOffset;
    image = document.getElementById('img2');
    image.style.zIndex=-1;
    image.style.top= ypos* .8 +'px';
}
if(screenY<=970) window.addEventListener('scroll',parallex);
else window.addEventListener('scroll',parallex2);
HTML

<img src="ny.jpg" id="img1" >
<img src="5429c32b425f183f61bf7316_new-york-city-skyline.jpg" id="img2" >
<img src="9OEWK8nMTFmqQwAFpFyn7snIGP8.jpg" id="img3">

这是javascript/canvas中的三幅视差图像。你可以根据自己的需要修改它。

var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var img3 = document.getElementById('img3');
var can = document.getElementById('can');
var w = can.width = img1.width = img2.width = img3.width = 200;
var h = can.height = img1.height = img2.height = img3.height = 100;
drawImages();
// SPEEDS
var s1 = .05;
var s2 = .25;
var s3 = 2;
// POSITIONS
var x1 = 0;
var x2 = 0;
var x3 = 0;
var ctx = can.getContext('2d');
function ani() {
  ctx.fillStyle = "#6699CC";
  ctx.fillRect(0, 0, w, h); // DRAW SKY
  ctx.drawImage(img3, x1, 0); // SHOW ONLY ONE MOON
  // OTHER IMAGES REPEAT
  ctx.drawImage(img1, -w + x2, 0);
  ctx.drawImage(img1, x2, 0);
  ctx.drawImage(img2, x3, 0);
  ctx.drawImage(img2, -w + x3, 0);
  x1 += s1;
  x2 += s2;
  x3 += s3;
  if (x1 > w) x1 = 0 - w; // SHOW ONLY ONE MOON
  if (x2 > w) x2 = 0;
  if (x3 > w) x3 = 0;
  requestAnimationFrame(ani);
}
ani();
function drawImages() {
  var ctx1 = img1.getContext('2d');
  ctx1.beginPath();
  ctx1.moveTo(0, h);
  ctx1.lineTo(20, 20);
  ctx1.lineTo(40, h - 10);
  ctx1.lineTo(80, 10);
  ctx1.lineTo(120, h);
  ctx1.lineTo(160, 30);
  ctx1.lineTo(200, h);
  ctx1.fillStyle = "#996600";
  ctx1.fill();
  var ctx2 = img2.getContext('2d');
  ctx2.fillStyle = "#666666";
  ctx2.moveTo(30, h);
  ctx2.lineTo(30, 0);
  ctx2.lineTo(45, 0);
  ctx2.lineTo(45, h);
  ctx2.rect(100, 50, 25, 50);
  ctx2.rect(w - 20, 0, 20, h);
  ctx2.fill();
  var ctx3 = img3.getContext('2d');
  ctx3.moveTo(50, 50);
  ctx3.arc(25, 25, 20, 0, 360 * Math.PI / 2);
  ctx3.fillStyle = "#FFFF00";
  ctx3.fill();
}
body {
  background-color: #ACE;
}
<canvas id="img1"></canvas>
<canvas id="img2"></canvas>
<canvas id="img3"></canvas>
<canvas id="can"></canvas>