一、效果图
想找游戏相干素材
二、间接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas 垂直背景图滚动 </title>
</head>
<body>
<canvas id="canvas" width="480" height="720">
你的浏览器不反对 canvas,请降级你的浏览器。</canvas>
<script>
const canvas = document.getElementById('canvas')
let ctx = canvas.getContext("2d")
var offSetY = 0;
var image = new Image(); // 创立图片元素
image.onload = function(){bgMove(image);
}
image.src = 'images/bg.jpg';
function bgMove() {
// 记录状态
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(0, offSetY);
ctx.drawImage(image, 0, 0);
ctx.drawImage(image, 0, -canvas.height);
// 判断 offSetY 偏移量
offSetY += 0.2;
if(offSetY >= canvas.height) {offSetY = 0;}
ctx.restore();
window.requestAnimationFrame(bgMove);
}
</script>
</body>
</html>
三、目录构造
图片能够在这里找背景图片地址