JSFiddle - React, Tailwind, and code Playground
by rockmanxdi
HTML
<body onload="reset();">
<main>
<!-- place your HTML code within the main -->
<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>
</main>
</body>
JavaScript
let surface=document.getElementById("drawingArea");
let ctx=surface.getContext("2d");
let cor_x;
let cor_y;
/** draw a cat
* input the coordinates x and y for the center of the cat
* does not return, output the drawing only.
*/
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);