删除旧的fillRect,clearRect无法正常工作?

时间:2018-07-10 16:48:22

标签: javascript canvas

我正在尝试使此代码正常工作,我正在尝试制作一个游戏,在其中单击消失的矩形,并取得了一些不错的进展,但是我的问题是,当矩形消失时,可以这么说。

我对canvas还是很陌生,但是我认为这与上下文中的clearRect方法有关,但是我不确定。这是我的代码:

             
<script>
const CANVAS_HEIGHT = 800;
const CANVAS_WIDTH = 1200;

var elem = document.getElementById('myCanvas'),
    elemLeft = elem.offsetLeft,
    elemTop = elem.offsetTop,
    context = elem.getContext('2d'),
    elements = [];


// Game vars
var score = 0;
var interval = 1000;
var wid = 150;
var hei = 100;

// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
    var x = event.pageX - elemLeft,
        y = event.pageY - elemTop;
    console.log(`Clicked at (${x}, ${y})`);


    // Collision detection between clicked offset and element.
    elements.forEach(function(element) {
        if (y > element.top && y < element.top + element.height 
            && x > element.left && x < element.left + element.width) {
                score += 1;
                wid -= 5/wid;
                hei -= 5/hei;
                console.log(`Score: ${score}`);
        }
    });

}, false);


// Add element.
function addElements(){
    var wp = Math.floor(Math.random() * CANVAS_WIDTH);
    var hp = Math.floor(Math.random() * CANVAS_HEIGHT);

    // Get rekt
    elements.push({
        colour: '#05EFFF',
        width: wid,
        height: hei,
        top: hp,
        left: wp
    });
    // Render
    elements.forEach(function(element) {
        context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
        context.fillStyle = element.colour;
        context.fillRect(element.left, element.top, element.width, element.height);
    });
}

(function myLoop (i) {          
   setTimeout(function () {   
      addElements();          //  your code here                
      if (--i) myLoop(i);      //  decrement i and call myLoop again if i > 0
   }, interval)
})(100);       


</script>

1 个答案:

答案 0 :(得分:0)

您永远都不会删除任何元素。

尝试在console.log(elements.length);内添加myLoop,然后观察计数器的上升情况:)

一个快速修复方法是将elements重新分配给addElements顶部的空数组

elements = [];