【问题标题】:Exact clearRect on moving clipped image on canvas在画布上移动剪切图像上的精确 clearRect
【发布时间】:2017-03-06 09:03:03
【问题描述】:

我正在尝试使用画布在 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);
    }
});

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    全画布动画重绘一切。

    在渲染包含许多元素的画布动画(例如游戏)时,最有效的渲染方法是每帧重绘所有内容。

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

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

    在除少数设备之外的所有设备上,大多数渲染都是通过 GPU 完成的,并且速度非常快(注意这不适用于 moveTo、lineTo、阴影、弧线、文本、椭圆)清除和重新渲染所有内容都可以轻松完成在 1/60 秒内完成,创建流畅的高质量动画

    关于阴影的注意事项。不要使用 context2D 阴影,大多数浏览器和硬件都不能很好地做到这一点,并且可能会对性能造成重大影响。即使您为一张小图像渲染一个阴影,情况也是如此。最好预先渲染阴影,或者加载单独的阴影作为图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 2021-08-11
      • 1970-01-01
      相关资源
      最近更新 更多