Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Objects on html5 Canvas

I placed an text on html5 canvas object using fillText option, question is I need to move the text position or change the color of the text that is already rendered.

Shortly I need to know how to Manipulate particular child of canvas element

like image 772
Sandeep Manne Avatar asked Jun 01 '11 09:06

Sandeep Manne


People also ask

How do you move elements in canvas?

Moving elements to a different page To select multiple elements, hold Shift on your keyboard, and click to add other elements to the selection. Drag the elements to the new page thumbnail. You'll then be taken to it. Drag the elements into the canvas and position them on the page.

How do I move the canvas in HTML5?

The canvas moveTo() method is used to move the path to the specified point in the canvas, without creating a line. After calling the moveTo() method, we can use stroke() method to draw the path on the canvas. Syntax: context.


2 Answers

I've never tried it but I think this would be the way to do it.

var canvas = document.getElementById("canvas"); //get the canvas dom object
var ctx = canvas.getContext("2d"); //get the context
var c = {  //create an object to draw
  x:0,  //x value
  y:0,  //y value
  r:5; //radius
}
var redraw = function(){  // this function redraws the c object every frame (FPS)
  ctx.clearRect(0, 0, canvas.width, canvas.height); // clear the canvas
  ctx.beginPath();  //start the path
  ctx.arc(c.x, c.y, c.r, 0, Math.PI*2); //draw the circle
  ctx.closePath(); //close the circle path
  ctx.fill(); //fill the circle
  requestAnimationFrame(redraw);//schedule this function to be run on the next frame
}
function move(){  // this function modifies the object
  var decimal = Math.random() // this returns a float between 0.0 and 1.0
  c.x = decimal * canvas.width; // mulitple the random decimal by the canvas width and height to get a random pixel in the canvas;
  c.y = decimal * canvas.height;
}
redraw(); //start the animation
setInterval(move, 1000); // run the move function every second (1000 milliseconds)

Here is a fiddle for it. http://jsfiddle.net/r4JPG/2/

If you want easing and translations, change the move method accordingly.

like image 51
0xcaff Avatar answered Sep 19 '22 13:09

0xcaff


I think there is no object model behind the canvas, so you cannot access a "child object" like a "text object" and change it. What you can do is that you draw the text again with a different color that overwrites the "pixels" of the canvas. If you want to move the text, first you have to either clear the canvas or re-draw the text with a background/transparent color to get rid of the text in the previous position. Then you can draw the text in the new position.

like image 36
Tz_ Avatar answered Sep 17 '22 13:09

Tz_