MDN--canvas--循环全景照片

效果图:
在这里插入图片描述

代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas id="canvas" width="800" height="200"></canvas>
		<script>
			var ctx = document.querySelector('#canvas').getContext('2d');
			
			var canvasWidth = 800;		//画布的大小与HTML中一致
			var canvasHeight = 200;
			var x ,y = 0;				//用于表示图片坐标
			var dx = 0.75; 				//图片每次向右移动的距离
			var img = new Image();
			//图片地址https://mdn.mozillademos.org/files/4553/Capitan_Meadows,_Yosemite_National_Park.jpg
			img.src = 'Park.jpg';
			var imgWidth;				//图片宽度
			var imgHeight;				//图片高度
			var clearx;					//清理画布的宽度
			var cleary;					//清理画布的高度
			
			img.onload = function(){
				imgWidth = img.width;
				imgHeight = img.height;
				
				clearx = imgWidth > canvasWidth ? imgWidth : canvasWidth;
				cleary = imgHeight > canvasHeight ? imgHeight : canvasHeight;
				
				if(imgWidth > canvasWidth){
					x = canvasWidth - imgWidth;
				}else{
					x = 0;
				}
				requestAnimationFrame(draw);
			}
			
			function draw(){
				ctx.clearRect(0,0,clearx,cleary);
				ctx.save();
				// 图片宽度大于canvas宽度
				if(imgWidth > canvasWidth){
					// 只要第一幅图向右边移动一点就在左边画第二幅图
					// if(x > canvasWidth - imgWidth){
					// 在第一幅图向右边移动至0,在左边画第二幅图
					if(x >= 0){
						ctx.drawImage(img,x - imgWidth,y);
					}
					if(x >= canvasWidth){
						x = canvasWidth - imgWidth;
					}
				}
				// 图片宽度小于canvas宽度
				else{
					if(x - imgWidth + dx < 0){
						ctx.drawImage(img,x - imgWidth,y);
					}else{
						x = 0;
					}
				}
				ctx.drawImage(img,x,y);
				x += dx;
				ctx.restore();
				requestAnimationFrame(draw);
			}
			
		</script>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值