Html5 Canvas 实现滚动的图片

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<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>

 图片是运行的效果。

posted @   居无常  阅读(2333)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· 开发者新选择:用DeepSeek实现Cursor级智能编程的免费方案
· 【译】.NET 升级助手现在支持升级到集中式包管理
· 独立开发经验谈:如何通过 Docker 让潜在客户快速体验你的系统
· Tinyfox 发生重大改版
点击右上角即可分享
微信分享提示