Canvas基本动画-循环全景照片 原

2019-04-04 09:41:04 浏览数 (1)

这是MDN上面的一个的例子,展现一个自左向右滑动的全景图,例子中采用的图片是一个尺寸大于canvas的图片

代码语言:javascript复制
    <canvas id="canvas" width="800" height="200" style="background:#f2f2f2"></canvas>
    <script>
    var img = new Image();
    img.src = "images/Capitan_Meadows,_Yosemite_National_Park.jpg";
    var CanvasXSize = 800;
    var CanvasYSize = 200;
    var speed = 30;
    var y = 0;

    //main program
    var dx = 0.75;
    var imgW;
    var imgH;
    var x = 0;
    var clearX;
    var clearY;
    var ctx;

    img.onload = function() {
        imgW = img.width;
        console.log(imgW);
        imgH = img.height;
        if (imgW > CanvasXSize) { 
		x = CanvasXSize - imgW
		clearX = imgW 
		} else {
            clearX = CanvasXSize
        }
        if (imgH > CanvasYSize) { clearY = imgH } else {
            clearY = CanvasYSize
        }
        ctx = document.getElementById("canvas").getContext("2d");

        setInterval(draw, speed)
    }

    function draw() {
        ctx.clearRect(0, 0, clearX, clearY)
        
        // if image is <= Canvas size
        if (imgW <= CanvasXSize) {
		    //reset, start from beginning
            if (x > (CanvasXSize)) { x = 0; }
            //draw aditional image
            if (x > (CanvasXSize - imgW)) { ctx.drawImage(img, x - CanvasXSize   1, y, imgW, imgH); }
        } else {
		     //reset, start from beginning
            if (x > CanvasXSize) { x = CanvasXSize - imgW }
			 //draw aditional image
            if (x > CanvasXSize - imgW) { ctx.drawImage(img, x - imgW   1, y, imgW, imgH) }

        }
        //draw image
        ctx.drawImage(img, x, y, imgW, imgH);
		//x值不断变大
        x  = dx
    }

    </script>

代码解释:图片加载完成后,由于图片宽度大于画布的宽度,为X重新赋值,此时x为负数,并为clearX与clearY赋比较大的值,然后间隔执行绘制图片的函数,绘制图片时首先清空画布,根据x的值执行特定的代码,第一次由于x是负数,并不满足判断的条件,只执行ctx.drawImage(img, x, y, imgW, imgH);第二次x的值不断变大,先执行 ctx.drawImage(img, x - imgW 1, y, imgW, imgH) ,再执行ctx.drawImage(img, x, y, imgW, imgH);

简单的图示

查看动画效果

(adsbygoogle = window.adsbygoogle || []).push({});

0 人点赞