0

Ok so I have the following code running at 60hz (1000/60)

setInterval(update, 1000/60);

function makecard()
{
    base_image = new Image();
    base_image.src = 'cardbase.png';
    base_image.onload = function(){
        drawrect(798,398,4+275,4+183,"black");
        cc.drawImage(base_image, 800, 400);
    }

    base2_image = new Image();
    base2_image.src = 'card2base.png';
    base2_image.onload = function(){
        drawrect(165,398,4+275,4+183,"black");
        cc.drawImage(base2_image, 167, 400);
    }
}

function update(){
    makecard();
}

Which draws two images on a canvas.

The thing is that I have a mousemove and a mousedown event to check if the user clicks in the image but when I move the mouse outside the images both images flicker.

c.addEventListener('mousemove', function(evt) {
    mousePos = getMousePos(c, evt);
    console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);

    }, false);

c.addEventListener('mousedown', function() {
    if(mousePos.x >= 798 && mousePos.x <= 798 + 275 + 4 && mousePos.y >= 398 && mousePos.y <= 398 + 183 + 4){
            if(drawcardbool == false){
                drawcardbool = true;
                currentCard = Math.floor((Math.random() * 4) + 1)-1;
                counter = 5;
                var refreshIntervalId = setInterval(function(){
                counter = counter - 1;
                if (counter==0){
                clearInterval(refreshIntervalId);
                drawcardbool = false;
                } 
                }, 1000);
            }
        }
    }, false);

It got worse when I reduced the frame rate from 60 to 30 hz.

Someone help me!

Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74
  • Try using requestAnimationFrame to draw your frames when the monitor refreshes. https://developer.mozilla.org/nl/docs/Web/API/window/requestAnimationFrame If you'd provide a working snippet or jsfiddle, I can give you an example. – Tschallacka Mar 06 '17 at 16:45
  • Load your image(s) once in parent/global scope. reuse the image object in the draw loop. Setting the img src forces the browser to reload and decode the image. Depending on hardware this may take longer time than a single frame. Also consider using requestAnimationFrame as already suggested. –  Mar 06 '17 at 18:17
  • Thanks K3N I did load the images on the start and just render them every frame and it worked flawlessly – Theodore DaBeast Mar 06 '17 at 18:42

0 Answers0