canvas 图片显示问题

    <canvas id="canvas" width="1000" height="500" style="background:#333"></canvas>
    //html代码



     var canvas = document.getElementById('canvas'),
        cvs = canvas.getContext('2d');
    (function motion(){
        cvs.clearRect(0,0,canvas.width,canvas.height);//为什么加上这条就无法显示图片了?
        img();
        console.log(1)
        requestAnimationFrame(motion);
    })();
    function img(){
        var Img = new Image();
        Img.src = 'https://www.baidu.com/img/bd_logo1.png';
        Img.onload = function(){
            cvs.drawImage(Img,100,100);
        };
    };
    img();
阅读 3.6k
1 个回答

你的这个问题,是代码的问题。

首先,你要明确你的这几行代码的用意:

1. cvs.clearRect(0,0,canvas.width,canvas.height);//canvas橡皮擦功能,擦除canvas上的像素
2. img();//重新给canvas指定渲染的图片,这个
3. console.log(1);//log
4. requestAnimationFrame(motion);//requestAnimationFrame函数会重绘动画,所以motion函数会一直循环执行下去,你可以在控制台看到‘console.log(1)’一直在执行,打印1出来

为什么你加了第一行代码就不显示图片?原因是:

  1. img()函数中的Img.src = 'https://www.baidu.com/img/bd_logo1.png';是一个异步的过程

  2. 因为有第四行代码调用motion,motion会一直执行,clearRect一直在清空canvas上的像素,而img()的异步下载图片还没有下载下来,就被clearRect给擦除掉了。
    所以,图片一直显示不出来。

想让图片显示出来,可以把第四行代码去掉,或者把第一行去掉。

参考:
https://developer.mozilla.org...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题