在画布上移动剪裁图像时的精确clearRect

时间:2016-10-24 14:23:29

标签: javascript html5 canvas

我正在尝试使用画布在html / javascript中制作一个简单的侧面滚动避免游戏。有一些麻烦删除(clearRect)移动变量高度剪裁图像所以它也不会删除用户上面控制的精灵/图像,我可以让它删除图像上方/下方的所有内容,但无法找到如何完全删除移动阴影图像,因此在动画制作时也不会删除游戏中的英雄!

https://jsfiddle.net/6k354f5x/3/

目前香蕉也已清除,任何帮助将不胜感激!

//<canvas id="board" width="480" height="640"></canvas>

//Getting the canvas
var board = document.getElementById("board");
var cx = board.getContext("2d");

//Example Images
var pipe = new Image();
pipe.src = "http://www.appcycle.me/flappy/img/pipe.png";
var hero = new Image();
hero.src = "http://vignette2.wikia.nocookie.net/drunken-peasants-podcast/images/9/9c/Banana-in-8-bit.png/revision/latest?cb=20150821213530";

//Pipe randomness calculated from board height
var pipeVariation = Math.floor((Math.random() * 250) + 1);
var pipeY = 456;
var pipeX = 350; 

//interval
var timer = setInterval(function() { 

  //draw the hero
    cx.drawImage(hero, 0, 150);

    //clear the afterimage
    cx.clearRect(pipeX, 80, pipe.width / 1.6, pipe.height / 1.6);

  //move it on the X-axis some px
    pipeX -= 2;

  //draw the clipped pipe with some Y-axis placement variation from pipeVariation variable
    cx.drawImage(pipe,
                    0, -pipeY+pipeVariation, pipe.width, pipe.height,
                    pipeX, 80, pipe.width / 1.6, pipe.height / 1.6)

  //Temporary to keep pipe from running away while testing
    if (pipeX <= 0) {
        clearInterval(timer);
    }
});

1 个答案:

答案 0 :(得分:0)

全画布动画重绘所有内容。

渲染具有许多元素(如游戏)的画布动画时,最有效的渲染方法是每帧重绘一次。

在每一帧的开始处,您要么清除整个屏幕,要么在最后一帧的顶部绘制背景图像(与清除相同),然后按照从最低到最高的z-index的顺序逐个绘制游戏元素(其中最高元素位于所有其他元素之上)

这使得代码非常简单,而复杂的脏请求方案很快变得非常复杂,并且可能会降低性能。

除少数设备外,大部分设备都是通过GPU完成的,速度非常快(注意这不适用于moveTo,lineTo,阴影,圆弧,文本,椭圆)清除和重新渲染一切都很容易在1/60秒内完成,创造出流畅的高品质动画

关于阴影的注意事项。不要使用context2D阴影,大多数浏览器和硬件都不能很好地完成,并且可能会成为主要的性能影响。即使为一个小图像渲染一个阴影,也可以这样。最好先预渲染阴影,或者将单独的阴影加载为图像。

相关问题