How to move an HTML5 canvas drawing without receiving the mouse or keyboard position? Other way?

0

I'm learning canvas in HTML5. I was able to draw a circle, using JavaScript to move, I got through mouse events and the arrow keys. But I would like to know if you have how I determine this position through a variable or something else ?? Anyone have any ideas?

    
asked by anonymous 20.08.2014 / 09:19

2 answers

1

You can create an Interval that will increment variables, which would change the position of the object. Another option is to have an array of predefined positions, in the latter case you can use Math.random () and get random values.

    
23.08.2014 / 01:36
0

Well as colleagues have said, do you want to play a random value so that you can move alone or by a path creating an animation, or just put a fixed value?

If it is the first case, just change the variable that receives the value of the mouse or keyboard by the fixed value, if it is the animation (as I think it is), you have 2 options to play random values or add a trigger (trigger) so that every 'X seconds' for example the position of your drawing is updated in the drawing area giving the movement.

Currently there is 3 way to do this:
window.setTimeout : Call a function only 1x < br> window.setInterval : Call a function infinitely

window.requestAnimationFrame : This function has a similar function as the other two, the difference is too much that has been implemented in HTML5 and has a focus on animation so roughly it works better the processing of calls.

So the idea is that your browser is ready to fire one of these events that update the positions of the elements of the canvas, below I put a simple example of a circle, circling (rs) by the area of the 'canvas' .

<canvas id="seuCanvas" width="1024" height="780" style="border: 1px solid #000000;"></canvas>
<script>
// Inicia a chama do canvas no JS
var canvas = document.getElementById("seuCanvas"), context = canvas.getContext("2d");

var amimacao = 1000; // Tempo da animação (em milisegundos)
var radius = 15; // Determina o raio do circulo

// Monta o circulo no canvas com a posição
function desenhaCirculo() {
 // Calcula uma posição aleatória para o X
 var centerX = Math.floor((Math.random() * canvas.width) + 1);
 // Calcula uma posição aleatória para o Y
 var centerY = Math.floor((Math.random() * canvas.height) + 1);

 // Limpa e desenha o circulo na posição
 context.clearRect(0, 0, canvas.width, canvas.height);
 context.beginPath();
 context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
 context.fillStyle = "#00FF00";
 context.fill();
 context.lineWidth = 1;
 context.strokeStyle = "#00000";
 context.stroke();

 // Adiciona uma cahama a cada X milisegundos
 window.setTimeout(desenhaCirculo, amimacao);
}

// Adiciona movimento ao carregar a página
window.onload = desenhaCirculo;
</script> 
    
06.02.2016 / 17:42