I created a script that uses HTML input buttons to move the cat to the canvas. Each click moves the cat 10 pixels in the direction it is clicked (moveUp (); moveDown (); moveLeft (); moveRight ();). This script works great for the first 10-20 clicks, but then the cat eventually jumps or gets stuck in one place.
I have no idea why he is behaving this way. can anyone help?
The program is on jsfiddle, you can check it out
https://jsfiddle.net/rockmanxdi/h2sk2sjz/2/
JavaScript code is below:
let surface=document.getElementById("drawingArea"); let ctx=surface.getContext("2d"); let cor_x; let cor_y; let drawCat = function (x, y) { ctx.save(); ctx.translate(x, y); ctx.fillText("ฅ(*ΦωΦ*) ฅ", -20,-5); ctx.restore(); }; let updateCoordinate = function(x_increment,y_increment){ console.log("before:" + cor_x + "/" + cor_y); cor_x += 10 * x_increment; cor_y += 10 * y_increment; console.log("updated:" + cor_x + "/" + cor_y); }; let moveUp = function (){ updateCoordinate(0,-1); console.log(cor_x + "/" + cor_y ); ctx.clearRect(0,0,surface.width,surface.height); drawCat(cor_x,cor_y); }; let moveLeft = function (){ updateCoordinate(-1,0); console.log( cor_x + "/" + cor_y ); ctx.clearRect(0,0,surface.width,surface.height); drawCat(cor_x,cor_y); }; let moveRight = function (){ updateCoordinate(1,0); console.log( cor_x + "/" + cor_y ); ctx.clearRect(0,0,surface.width,surface.height); drawCat(cor_x,cor_y); }; let moveDown = function (){ updateCoordinate(0,1); console.log(cor_x + "/" + cor_y ); ctx.clearRect(0,0,surface.width,surface.height); drawCat(cor_x,cor_y); }; let reset = function(){ cor_x=surface.width/2.0; cor_y=surface.height/2.0; console.log(cor_x + "/" + cor_y ); ctx.clearRect(0,0,surface.width,surface.height); drawCat(cor_x,cor_y); } drawCat(200,200);
html body:
<canvas width="400" height="400" id="drawingArea" style="border:solid">cat image</canvas> <p> <input type="button" id="resetBtn" value="reset" onclick="reset();" /> </p> <p> <input type="button" id="upBtn" value="Up" onclick="moveUp();"/> </p> <p> <input type="button" id="leftBtn" value="Left" onclick="moveLeft();"/> <input type="button" id="rightBtn" value="Right" onclick="moveRight();"/> </p> <p> <input type="button" id="downBtn" value="Down" onclick="moveDown();"/> </p>
By the way, I put console.log () inside updateCoordinate (); and move UP / Down / Right / Left (); functions for tracking x and y coordinates of a cat. Press F12 to track the value.