美文网首页
canvas绘制图片问题

canvas绘制图片问题

作者: 斐硕人 | 来源:发表于2016-11-29 23:35 被阅读0次

    周六参加了 Learn Smart 活动,学习制作了“太空船躲避宇宙碎片”小游戏。
    <a href="https://bbs.excellence-girls.org/uploads/files/1480164873193-%E8%B5%B5%E6%82%A6%E5%A6%AE%E7%BB%84.pdf">小组协作文档</a>
    <a href="https://jsbin.excellence-girls.org/qoqo/1/edit?html,js,console,output">与搭档最终做出的游戏</a>
    之后反复的看这个游戏,觉得还是换成图片好看点(木有错,就是要这么花哨)。找了一下绘制图片的代码,如下:

        var img = new Image();
        img.onload = function(){
          ctx.drawImage(img,airShip.x,airShip.y,40,40);
        }
        img.src = 'http://peps-deratisation.com/images/icon_27457-300x300.png';
    
    

    傻傻的我就傻傻的直接替换用了。。。。
    当时的代码如下:

    function creatShip(){
      ctx.fillStyle="#F08080";
      ctx.fillRect(airShip.x,airShip.y,20,20);
    }
    
    

    替换后的代码:

    function creatShip(){
        var img = new Image();
        img.onload = function(){
          ctx.drawImage(img,airShip.x,airShip.y,40,40);
        }
        img.src = 'http://peps-deratisation.com/images/icon_27457-300x300.png';
    
    }
    

    游戏地址:https://jsbin.excellence-girls.org/xul/1/edit?output
    没想到替换后出现了新的问题就是图片不断的闪烁。
    查了一下这个问题,发现很多人提出的解决方式是双缓冲。。。然而智商受限的我并木有get到这个解决方法。
    突然瞄到有个人说是不断重绘的原因,解决方式大致就是提前画好,之后每次调用画好的图片。
    看了一下自己之前的代码,默默地改了一下,先在最前面定义好了如下代码(改了变量和函数名字,不要在意这些细节)

    const mouseImg = new Image();
    const rattrapImg = new Image();
    
    
    mouseImg.src = 'http://peps-deratisation.com/images/icon_27457-300x300.png';
    rattrapImg.src = 'http://i0.hdslb.com/bfs/archive/b1a3cf16937a21eefb6189f5df474201f86ff678.jpg';
    
    

    然后函数就变成如下的样子

    function creatMouse(x, y){
        ctx.drawImage(mouseImg,x,y,40,40);
    }
    
    function creatRattrap(x, y){
    
        ctx.drawImage(rattrapImg,x,y,40,40);
    
    }
    

    然后的然后,图片就木有再闪了。
    游戏地址:https://jsbin.excellence-girls.org/fij/edit?output
    代码地址:https://github.com/egrils/canvas-demo/tree/master/mouse%26rattrap

    相关文章

      网友评论

          本文标题:canvas绘制图片问题

          本文链接:https://www.haomeiwen.com/subject/bviapttx.html