-1

When running my program I have an image I want to draw on the mouse's x position(clientX) and y position(clientY). When running the program regularly by not using client x and y in the position for being drawn, it works just fine.

This is the image

//variables
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var player = new Image();
player.src = "https://i.stack.imgur.com/P9vJm.png";


//functions
function start() {
 setInterval(update, 10);
}
function update() {
 clearRender();
 render();
}

function clearRender() {
 ctx.clearRect(0,0,1300,500);
}
function render() {
 var mx = document.clientX;
 var my = document.clientY;
 ctx.drawImage(player, mx, my);
}
#canvas {
 height: 500px;
 width: 1300px;
 background-color: black;
 position: absolute;
 left: 25px;
 top: 50px;
}
body {
 background-color: white;
}
<!DOCTYPE html>
<html>
<head>
 <title> Space Invaders </title>
 <link rel="stylesheet" type="text/css" href="invader.css">
</head>
<body>
 <canvas id="canvas"> </canvas>
 <script type="text/javascript" src="invader.js"></script>
</body>
</html>
le_m
  • 19,302
  • 9
  • 64
  • 74
Henry Redder
  • 27
  • 1
  • 11

1 Answers1

0

To get you started, you would need an event handler to get your mouse position

c.addEventListener('mousemove', update, false);

JS:

//variables
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var player = new Image();
player.src = "https://i.stack.imgur.com/P9vJm.png";

c.addEventListener('mousemove', update, false);

//functions
function start() {
  setInterval(update, 10);
}

function update(e) {
  //clearRender();
  render(e);
}

function clearRender() {
  ctx.clearRect(0, 0, 1300, 500);
}

function render(e) {
  var pos = getMousePos(c, e);
  posx = pos.x;
  posy = pos.y;
  ctx.drawImage(player, posx, posy);
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

Here's a fiddle: https://jsfiddle.net/vwbo8k6k/

This might help you understand more about mouse positions, but I hope the image shows this time.

http://stackoverflow.com/a/17130415/2036808

dariru
  • 501
  • 6
  • 16