Well, this edition works for me. Add imgWidth
imgHeight
vars, instead of numerical values, add width and height to each canvas redraw, and fixed positioning of img on keypress.
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="https://stackoverflow.com/questions/47010515/css/reset.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
body {}
canvas {
border: 1px;
}
</style>
<script>
$(function() {
var imgWidth = 128;
var imgHeight = 120;
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
};
img.src = "http://www.earthtimes.org/newsimage/eating-apples-extended-lifespan-test-animals-10-per-cent_183.jpg";
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var isDragging = false;
function handleMouseDown(e){
canMouseX=parseInt(e.clientX-offsetX);
canMouseY=parseInt(e.clientY-offsetY);
// set the drag flag
isDragging=true;
}
function handleMouseUp(e){
canMouseX=parseInt(e.clientX-offsetX);
canMouseY=parseInt(e.clientY-offsetY);
// clear the drag flag
isDragging=false;
}
function handleMouseOut(e){
canMouseX=parseInt(e.clientX-offsetX);
canMouseY=parseInt(e.clientY-offsetY);
// user has left the canvas, so clear the drag flag
//isDragging=false;
}
function handleMouseMove(e) {
canMouseX = parseInt(e.clientX - offsetX);
canMouseY = parseInt(e.clientY - offsetY);
// if the drag flag is set, clear the canvas and draw the image
if (isDragging) {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.drawImage(img, canMouseX - (imgWidth / 2), canMouseY - (imgHeight / 2), imgWidth, imgHeight);
}
}
function handleKeyPress(e) {
if (e.which == 32) {
canKeybX = (canvasWidth-imgWidth) * Math.random();
canKeybY = (canvasHeight-imgHeight) * Math.random();
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.drawImage(img, canKeybX, canKeybY, imgWidth, imgHeight);
}
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").keydown((function(e) {
handleKeyPress(e);
}));
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=1300 height=800 tabindex='1'></canvas>
</body>
</html>
3
solved Moving an object randomly on keypress