80183

HTML5 Canvas Image Moving Flickering

Question:

In canvas, there is a image, which moves on events of arrow keys. But it flickers in firefox and works fine on chrome and ie.

I don't want a solution like to clear only the portion of canvas, because I have other things added in canvas too.

Below is my code:

var velY = 0, velX = 0, speed = 2, friction = 0.90, keys = [], canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"), playerDirection="img/player/player_back.png"; function update() { if (keys[38]) { if (velY > -speed) { velY--; playerDirection="img/player/player_back.png"; } } if (keys[40]) { if (velY < speed) { velY++; playerDirection="img/player/player_front.png"; } } if (keys[39]) { if (velX < speed) { velX++; playerDirection="img/player/player_right.png"; } } if (keys[37]) { if (velX > -speed) { velX--; playerDirection="img/player/player_left.png"; } } velY *= friction; y += velY; velX *= friction; x += velX; if (x >= canvas.width - player.width) { x = canvas.width - player.width; } else if (x <= 5) { x = 5; } if (y > canvas.height - player.height) { y = canvas.height - player.height; } else if (y <= 5) { y = 5; } ctx.clearRect(0, 0, canvas.width, canvas.height); playerObj = new Image(); playerObj.onload = function() { ctx.drawImage(playerObj, x, y); }; playerObj.src = playerDirection; } update(); function handlerKeyDown(e) { keys[e.keyCode] = true; } function handlerKeyUp(e) { keys[e.keyCode] = false; }

Thanks in adavance.

Answer1:

This is what I meant with "caching the images":

var images = {}; // This will contain the Image objects // Other definitions... function update() { if (keys[38]) { if (!images.back) { // The image object hasn't been defined yet. images.back = new Image(); images.back.src = "img/player/player_back.png"; } playerObj = images.back; } // Other checks on the pressed keys // ... // Computations on the position... if (!playerObj.naturalWidth) { // If naturalWidth/Height is 0, then the image hasn't been loaded yet. // We update the onload listener to draw in the right position. playerObj.onload = function() { ctx.drawImage(playerObj, x, y); }; // The image has already been loaded, so we just draw it } else ctx.drawImage(playerObj, x, y); }

(As an warning on your code, it seems that you want to handle multiple pressed keys, but the last one in the sequence up-down-right-left always "wins" over the others. Is that really what you want?)

Recommend

  • Not able to apply impulse to SKSpriteNode physics body
  • How to override/extend an inner class from a subclass?
  • What is the 'f' used for in JBox-2d? [duplicate]
  • Filters in HBASE
  • fullrange = TRUE ignored in stat_smooth
  • NaNs produced in negative binomial regression when using dnbinom()
  • SKSpriteKit maintaining constant velocity after collision
  • Iterating over the big matrix containing 3000 rows and calculate the correlation
  • Get byte[] from
  • How to Filter ListAdapter using getFilter() within a fragment
  • IndexSizeError on drawImage on IE and Edge
  • Chart js - Draw center of each bubbles of a bubble chart
  • $_POST for text in DIV elements
  • pythonanywhere - How do I use websockets to transmit messages as per the web2py messaging example?
  • how to ignore xml namespaces?
  • Is looping through all style sheets and classes a good idea in JavaScript?
  • Making Google Visualization - Annotation Chart to work in GWT
  • Python PIL to extract number from image
  • Cannot get text from text area
  • HTML5 video only works in IE. The other browsers shows the black screen
  • Outputting SharePoint Hyperlink Column as URL
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • How can I restyle a word when rendering a pdf with pdf.js?
  • Update Google Maps traffic layer without page reloading
  • Uncaught TypeError: $(…).select2 is not a function
  • Disable Kendo Autocomplete
  • Remove changes from one element when event occurs on another element?
  • close() was never explicitly called on database
  • How to view images from protected folder with php?
  • Button click event not firing in jQuery
  • Chart.js Multiple dataset
  • How do I get HTML corresponding to current DOM tree?
  • How to render a blob on a canvas element?
  • JQuery Internet Explorer and ajaxstop
  • JSON response opens as a file, but I can't access it with JavaScript
  • MySQL WHERE-condition in procedure ignored
  • Change an a tag attribute in JavaScript based on screen width
  • Adding custom controls to a full screen movie
  • EntityFramework adding new object to nested object collection
  • playing video using jmf