Simple HTML5 canvas problem

I’ve loaded an image into HTML5 canvas. But I’m trying to move it across the page and it just stays there. My code LOOKS good to me, but I just cant’ seem to figure out why the image won’t move!

<!doctype html>
<html>
<head>
<meta charset=“UTF-8” />
<title>Canvas Test</title>
</head>
<body>
<section>
<div>
<canvas id=“canvas” width=“800” height=“600”>
This text is displayed if your browser
does not support HTML5 Canvas.
</canvas>
</div>


<script type="text/javascript">
var canvas;  
var ctx;
var newx = 700;
var newy = 200; 
  



function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  return setInterval(draw, 10);
}



var myImage = new Image();
myImage.src = "knight.png";

myImage.onload = function() {
ctx.drawImage(myImage, newx, newy);
}


function draw() {
clear(); 
ctx.save();
  
ctx.drawImage(myImage,newx,newy); 
newx--; 
 
ctx.restore(); 
 

}

init();
</script>


</section>
</body>
</html>

OH AND BY THE WAY… THROUGH TESTS I’VE FOUND OUT THAT IT’S NOT EVEN CALLING THE ‘DRAW’ FUNCTION AT ALL… but I’ve seen other scripts do it this way… what am I doing wrong?

This line doesn’t appear to be valid.


clear(); 

Ah… thank you sir !

So yes, deleting that line, the image now moves!!!

but it stamps a million images as it glides across, as the graphics buffer has not been cleared so the previous images stay while new ones are remaining.

since there is no “clear” function, what function do we use to clear the previous image each frame?

I think that you now know that just removing the clear() line isn’t going to solve your problem. You still need the screen to clear.

So instead of deleting that line, there is something else that you could add instead, so that clear() works correctly.

Yes, that’s my question… what’s the command for html5 to clear the graphics buffer.

I’ve tried looking for a comprehensive list of html5 canvas commands, but somehow in the lists I’ve found I have not found the one to clear bitmap graphics that are drawn to the screen. it obviously exists so I need a nudge in that direction.

Google search for html5 canvas animation and you find:
How to Draw with HTML 5 Canvas

Scroll down and you find the bouncing balls demo. Look at the code for that demo. There you will find how to handle clear()

I see … THANKS… i had seen that function but I thought it only pertained to vector images drawn with canvas and not imported images… but now I see that it clears the canvas in general.

thank you !