码迷,mamicode.com
首页 > Web开发 > 详细

Html5 Canvas 实现滚动的图片

时间:2015-09-16 17:34:16      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

今天一直在找html5 canvas的使用实例。想画一张地图,再画个小车在上面跑。运气好找到了一个大神写的js代码。该代码实现了图片的左右来回滚动,现在粘贴在博客里记录一下:

<html>
<head>
<meta charset="utf-8" />
<title>LScroll5.html</title>
<script type="text/javascript">
	var LScroll = {
		img : null,
		sc : null,
		scx : null,
		at : 0,
		flag : true,
		loadImg : function(srcs, callback) {
			var mg = new Image();
			mg.src = srcs;
			mg.onload = function() {
				callback(this);
			}; // callback function
			return LScroll.img = mg;
		},
		init : function(srcs) {
			if (!document.body)
				document.createElement(‘body‘);
			if (!LScroll.sc) {
				var sc = document.createElement(‘canvas‘);
				LScroll.scx = sc.getContext(‘2d‘);
				var callback = function(imgs) { // after onload image can be draw
					sc.width = imgs.width / 4;
					sc.height = imgs.height; //not style.
					sc.style.backgroundColor = ‘black‘;
					sc.style.border = ‘solid 1px white‘;
					document.body.style.backgroundColor = ‘black‘;
					document.body.style.textAlign = ‘center‘;
					document.body.appendChild(LScroll.sc = sc);
					LScroll.draw(LScroll.sc, LScroll.scx);
				};
				LScroll.loadImg(srcs, callback);
			}
		},
		draw : function(sc, scx) {
			scx.clearRect(0, 0, sc.width, sc.height);
			scx.save();
			scx.beginPath();

			switch (LScroll.flag) {
			case true:
				if (-LScroll.at == LScroll.img.width - sc.width)
					LScroll.flag = !LScroll.flag;
				LScroll.at--;
				break;
			case false:
				if (LScroll.at == 0)
					LScroll.flag = !LScroll.flag;
				LScroll.at++;
			}

			scx.drawImage(LScroll.img, LScroll.at, 0);
			scx.restore();
			setTimeout(function() {
				LScroll.draw(sc, scx);
			}, 10);
		}
	};
	window.onload = function() {
		LScroll.init(‘road-map.png‘);
	};
</script>
</head>
<body>

</body>
</html>

 图片是运行的效果。技术分享

Html5 Canvas 实现滚动的图片

标签:

原文地址:http://www.cnblogs.com/guxingzhe/p/4813509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!