Rotate text in a canvas with javascript - javascript

In the following code i want to rotate the text of each element of the array in javascript. If i use for example ctx.rotate(Math.PI/10) before the filltext, it rotates all the elements. The positioning of the text also changes with ctx.rotate(Math.PI/10) and if i use 90 degrees, ctx.rotate(Math.PI/2) the text does not show on the canvas.
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
ctx.rotate(Math.PI/10);
for(var i = 0; i < x.length; i++){
ctx.fillText(x[i],i*50+20,50);
}
</script>
</html>
As i said, i want to rotate each element on its own and with that the positioning of each element should stay the same as in the non-rotated text as in the code above. Thus each element has to rotate around its own axis. How can i achieve this?

Have made some changes in your code, it should help:
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
for(var i = 0; i < x.length; i++){
var size = ctx.measureText(x[i]);
ctx.save();
var tx = (i*50+20) + (size.width/2);
var ty = (50);
ctx.translate(tx,ty);
ctx.rotate(Math.PI / 10);
ctx.translate(-tx,-ty);
ctx.fillText(x[i],i*50+20,50);
ctx.restore();
}
</script>
</html>

Demo: http://jsfiddle.net/m1erickson/YyN2P/
A brief overview:
context.translate to where you want the rotation point of the text
context.rotate
context.fillText with an X offset == 1/2 the text width and Y offset == 1/2 the text height
(you can context.measureText to measure the text width)
wrap all this in context.save and context.restore.
use requestAnimationFrame to drive your animation.
And some example code:
var word1="Day1";
var word1Width=ctx.measureText(word1).width;
var r=0;
animate();
function animate(){
requestAnimationFrame(animate);
r+=Math.PI/180;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(100,100);
ctx.rotate(r);
ctx.fillText(word1,-word1Width/2,4);
ctx.restore();
}

Related

HTML5 Canvas - drawing fails once shifting the current browser tab

Ok, I've noticed this bug happen not only in the following code(which is just to illustrate), but every code I've written for canvas;
basically, in chrome(I didn't test other browsers),
once you shift your current tab to either a different pc screen, or simply if you have a few tabs in a row and decide to make a new window out of your current tab,
the canvas itself fails to draw. it is stuck and no reason is given in the console.
Here is a GIF of it happening:
http://gifmaker.cc/PlayGIFAnimation.php?folder=2016081601ZEuvXaZnxC2T9fHNNqSW3l&file=output_f72O1H.gif
Just a simple canvas code if you want to try it out:
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
<script>
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// inital coordinates of the black square
var x = 0;
var y = 200;
// speed of the movement in x- and y-direction
// actual no movement in y-direction
var vX = 1;
var vY = 0;
// width and height of the square
var width = 10;
var height = 10;
function animate() {
// clear
// comment this clear function to see the plot of the sine movement
ctx.clearRect(0, 0, canvas.width, canvas.height);
x += vX;
y += vY;
// if the block leaves the canvas on the right side
// bring it back to the left side
if(x>500) {
x = 0;
}
ctx.fillRect(x, y, width, height);
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();
</script>
Some sites fixed this bug but I don't know if I am allowed to link them here.

Html5 canvas animation. How to reset rectangle when it hits the end

Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/

How to set height on canvas after filled some text?

I'm filling canvas with some dynamic texts in ArrayList. And I set the height as length of ArrayList like ArrayList.length * 20 or something like that.
HTML:
<canvas id="myCanvas" width="272px" style="border: 1px solid black"></canvas>
JS :
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var myheight = 10;
for(var i = 0; mylist.length > i; i++){
context.fillText("my text", 10, myheight);
myheight += 10;
}
loop works fine, texts are filled.. and I'm trying to calculate the canvas.height after the loop.
When I set canvas.height = myheight and all filled texts are gone.. canvas gone blank.
How can I set height after canvas filled by texts dynamically?
Help me..
Thank you.. And sorry for bad English..
Resizing window or canvas using canvas.height = myheight clears the canvas
you need to sava the content of canvas and redraw it again on the resized canvas
If you want to save the content of the canvas and redraw it,here is few options
Use context.getImageData to grab the whole canvas, resize the
canvas, then use context.putImageData to redraw it at the new scale.
Create a new canvas with the updated size and call
context.drawImage(oldCanvas, ...) to copy the old canvas onto the
new one.
call context.setScale(xscale, yscale) and call whatever function you
used to draw the canvas originally. Assuming you set up xscale and
yscale correctly, it will automatically scale everything to the new
size.
A quick solution to your problem is to calculate canvas height before drawing the text, because as you use canvas.height the canvas will be erased
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var myheight = 10;
for(var i = 0; 10 > i; i++){
myheight += 10;
}
canvas.height = myheight;
myheight = 10;
for(var i = 0; 10 > i; i++){
context.fillText("my text", 10, myheight);
myheight += 10;
}
http://jsfiddle.net/borja204/66dn06tq/1/

How to make a counter using a canvas in javascript

I'm trying to make a counter so that every time you click your mouse it shows the number of clicks in the canvas. But it isn't updating the canvas.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<button onclick="function1()">Click Here</button>
<script>
var animate = setInterval(window.requestAnimationFrame,1)
var clicks = 0;
function function1()
{
clicks++;
document.getElementById('myCanvas').innerHTML = clicks;
};
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
</script>
</body>
</html>
So I changed the code to add a redraw() function to redraw on the canvas the new number.
And the increment() function will call that one after doing clicks++.
var clicks = 0;
function increment(){
clicks++;
redraw();
};
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
console.log(ctx);
function redraw(){
ctx.clearRect(0, 0, c.width, c.height);
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
}
redraw();
You can't just use innerHTML for canvas because it is really just a surface for drawing on thus it is not affected by it's inner DOM.
Here is a working JSFiddle demo.
Your code throws an error, window.requestAnimaitonFrame requires a callback to a function as parameter. This code works:
var animate = setInterval(function(){update()},1)
var clicks = 0;
function function1()
{
clicks++;
};
function update(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.clearRect(0,0,c.width,c.height);
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
}

Image is flickering continuously in pressing button?

The Image is flickering as I continuously push the button. The problem might be in ctx.clearRect(0,0,100,500) . How can I resolve the problem?
I am trying to animate in HTML 5 canvas.
I need a moving object in canvas and when I push the button, the other moving object follow the previous without flickering.
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,100,500); // This may be the problem
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
HTML 5
<button onclick="draw(0,500)">Draw</button>
<canvas id="canvas" width="600" height="500">
</canvas>
It looks like the problem may be because you aren't clearing the entire canvas. Try this:
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
Demo
The image flicker when you press the button more than once, which means you start the setTimeout() more than once. Add a variable to check if it's already been pressed.

Categories

Resources