zoukankan      html  css  js  c++  java
  • Html5 Canvas 实现滚动的图片

    今天一直在找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>
    

     图片是运行的效果。

  • 相关阅读:
    JDK类集框架实验(ArrayList,LinkedList,TreeSet,HashSet,TreeMap,HashMap)
    iOS 常见小问题
    yii自己定义CLinkPager分页
    Java获取项目路径下的方法(全)
    公布自己的pods到CocoaPods trunk 及问题记录
    虚拟化技术对照:Xen vs KVM
    jsp的凝视可能会影响页面载入速度
    重载与覆盖的差别
    Android程序全然退出的三种方法
    百度地图3.2教程(2)公交查询
  • 原文地址:https://www.cnblogs.com/guxingzhe/p/4813509.html
Copyright © 2011-2022 走看看