Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...