I want to have a animated canvas rotation of a word, while another word on the canvas does not move. But somehow both stand still. What do I have to change?
[link]http://jsfiddle.net/2dszD/8/
var canvas;
var ctx;
var canvasWidth;
var canvasHeight;
var interval = 10;
function init(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
canvasWidth = canvas.width;
canvasHeight = canvas.height;
setInterval(redraw, interval);
}
init();
function redraw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.translate( (200 ), (150 ) );
ctx.rotate( 1*Math.PI/180 );
ctx.fillStyle = '#f00';
ctx.font = '40px san-serif';
ctx.textBaseline = 'top';
ctx.fillText("Hello rotated", 0, 0);
ctx.rotate(-( 1*Math.PI/180 ));
ctx.translate( -(200), -(150) );
ctx.fillStyle = '#f00';
ctx.font = '40px san-serif';
ctx.textBaseline = 'top';
ctx.fillText("Hello still", 0, 0);
}
Actually, your text is rotated by a tiny 1.0 degree.
1*Math.PI/180 represents 1 tiny degree of rotation
So this would be a more noticeable 5 degrees:
ctx.rotate( 5.0 * Math.PI/180 );
A few coding glitches:
You need to increment the rotation angle so your text actually animates
angleInDegrees+=5;
ctx.rotate( angleInDegrees * Math.PI/180 );
setInterval requires a full function as an argument, not just a function name, like this:
setInterval( function(){redraw();}, interval);
And here’s easier way to handle translate/rotate
Instead of un-translating and un-rotating like this:
ctx.translate( (200 ), (150 ) );
ctx.rotate( 1*Math.PI/180 );
// draw stuff here
ctx.rotate(-( 1*Math.PI/180 ));
ctx.translate( -(200), -(150) );
You can instead context.save() and context.restore() which is cleaner and doesn’t require un-doing:
// save the canvas context—including its un-translated and un-rotated setting
ctx.save();
ctx.translate(200,150);
ctx.rotate( angleInDegrees * Math.PI/180 );
// draw stuff here
// after restore() the canvas is back to its starting position before save()
ctx.restore();
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/5XTcn/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvasWidth;
var canvasHeight;
var interval = 350;
var angleInDegrees=0;
function init(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
canvasWidth = canvas.width;
canvasHeight = canvas.height;
setInterval( function(){redraw();}, interval);
}
init();
function redraw() {
angleInDegrees+=5;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.rect(200,150,5,5);
ctx.fill();
ctx.save();
ctx.translate(200,150);
ctx.rotate( angleInDegrees * Math.PI/180 );
ctx.fillStyle = '#f00';
ctx.font = '40px san-serif';
ctx.textBaseline = 'top';
ctx.fillText("Hello rotated", 0, 0);
ctx.restore();
ctx.fillStyle = '#f00';
ctx.font = '40px san-serif';
ctx.textBaseline = 'top';
ctx.fillText("Hello still", 0, 0);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=500 height=300></canvas>
</body>
</html>
Related
I have this simple canvas webpage that lets user upload photo from camera by using HTML input type file. The idea is to let user make free drawing on their image. However, I have one problem.
On some devices, the image from camera is drawn onto the canvas with wrong orientation, so I have to provide users a button to rotate their image to get the drawing with correct orientation.
The problem is that after the canvas has been transformed and rotated to get the correct orientation, the drawing coordinates seems to be way off. For example, if I draw straight horizontal line, I get instead straight vertical line after the image has been rotated once. I think the problem lies in that fact that canvas orientation is changed.
So how can I correct back the drawing coordinate after image has been transformed and rotate? My code is below..
window.onload = init;
var canvas, ctx, file, fileURL;
var mousePressed = false;
var lastX, lastY;
function init(){
canvas = document.getElementById('myCanvas')
ctx = canvas.getContext('2d')
canvas.addEventListener('mousedown', touchstartHandler, false)
canvas.addEventListener('mousemove', touchmoveHandler, false)
canvas.addEventListener('mouseup', touchendHandler, false)
canvas.addEventListener('mouseleave', touchcancelHandler, false)
}
function touchstartHandler(e){
e.preventDefault()
mousePressed = true;
Draw(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, false);
}
function touchmoveHandler(e){
e.preventDefault()
if (mousePressed) {
Draw(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
}
}
function touchendHandler(e){
e.preventDefault()
if (mousePressed) {
mousePressed = false;
}
}
function touchcancelHandler(e){
e.preventDefault()
if (mousePressed) {
mousePressed = false;
}
}
function Draw(x, y, isDown) {
if (isDown) {
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.lineWidth = 12;
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
}
lastX = x;
lastY = y;
}
<!DOCTYPE html>
<html>
<head>
<title>Portrait</title>
</head>
<body>
<canvas id="myCanvas"></canvas><br/>
<input type="file" onchange="fileUpload(this.files)" id="file-input" capture="camera"><br/><br/>
<button onclick="rotate()">Rotate</button>
<script>
var file, canvas, ctx, image, fileURL;
function fileUpload(files){
file = files[0]
fileURL = URL.createObjectURL(file)
canvas = document.getElementById('myCanvas')
canvas.style.backgroundColor = "blue"
ctx = canvas.getContext('2d')
image = new Image()
image.onload = function() {
canvas.width = 500
canvas.height = (500*this.height)/this.width
ctx.drawImage(image,0,0,canvas.width,canvas.height)
ctx.save();
}
image.src = fileURL
}
function rotate(){
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.translate(canvas.width/2, canvas.height/2)
ctx.rotate(90*Math.PI/180)
ctx.translate(-canvas.width/2, -canvas.height/2)
ctx.drawImage(image,0,0,canvas.width,canvas.height)
}
</script>
</body>
</html>
You need to save the canvas state before rotating and translating, and then restore the state when the transformation is done.
var file, canvas, ctx, image, fileURL, rotation = 90;
function fileUpload(files) {
file = files[0]
fileURL = URL.createObjectURL(file)
canvas = document.getElementById('myCanvas')
canvas.style.backgroundColor = "blue"
ctx = canvas.getContext('2d')
image = new Image()
image.onload = function() {
canvas.width = 500
canvas.height = (500 * this.height) / this.width
ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
}
image.src = fileURL
}
function rotate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save(); //save canvas state
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(rotation * Math.PI / 180);
ctx.translate(-canvas.width / 2, -canvas.height / 2);
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
rotation += 90;
ctx.restore(); //restore canvas state
}
canvas {border: 1px solid red}
<canvas id="myCanvas"></canvas>
<br/>
<input type="file" onchange="fileUpload(this.files)" id="file-input" capture="camera">
<br/>
<br/>
<button onclick="rotate()">Rotate</button>
Simple rotation
Quickest way to rotate the image by steps of 90 deg
ctx.setTransform(
0,1, // direction of x axis
-1,0 // direction of y axis
canvas.width,0 // location in pixels of the origin (0,0)
);
Then draw the image
ctx.drawImage(image,0,0);
Rather than use ctx.restore() that can be slow in many situations you can eset only the transform to the default with.
ctx.setTransform(1,0,0,1,0,0);
Rotate 90, 180, -90deg
Thus to rotate 90 deg
ctx.setTransform(0,1,-1,0,canvas.width,0);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0);
Thus to rotate 180 deg
ctx.setTransform(-1,0,0,-1,canvas.width,canvas.height);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0);
Thus to rotate -90 deg
ctx.setTransform(0,-1,1,0,0,canvas.height);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0);
I have to create a rotation wheel with 12 fields like in the image below link :http://www.resilienciacomunitaria.org/
How i create through which approach?
I used canvas for this but not successful i used d3.js svg but not successful .
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="600" height="600"
style="background-color:#ffff">
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height /2; //400
//alert(radius);
//draw a circle again and agian
ctx.translate(radius, radius);
radius =radius*0.85;
setInterval(drawCircle, 50);
function drawCircle() {
var pos = .01;
var length = 100;
var width = 40;
drawFace(ctx, radius);
drawHand(ctx, pos, length, width);
}
function drawFace(ctx,radius){
ctx.beginPath();
ctx.arc(0, 0, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = '#ffff';
ctx.strokeStyle = 'blue';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI, false);
ctx.strokeStyle = 'yellow';
ctx.fillStyle = 'blue';
ctx.lineWidth = 50;
ctx.fill();
ctx.stroke();
}
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = 30;
ctx.moveTo(-radius,0);
ctx.lineTo(radius, 0);
ctx.moveTo(-radius,150);
ctx.lineTo(radius, -150);
ctx.moveTo(-radius,-150);
ctx.lineTo(radius, 150);
ctx.moveTo(-radius,380);
ctx.lineTo(radius, -380);
ctx.moveTo(-radius,-380);
ctx.lineTo(radius, 380);
ctx.moveTo(0, -radius);
ctx.lineTo(0, radius);
ctx.stroke();
/*
ctx.globalCompositeOperation='destination-over';
ctx.font="20px Verdana";
ctx.fillStyle = 'white';
ctx.fillText("Explore Zero",180,180);
ctx.stroke();
ctx.globalCompositeOperation='source-over';*/
ctx.rotate(-pos);
}
</script>
</body>
</html>
Thanks in advance
Here's code to get you started:
You can style it to your specific needs
Create an in-memory canvas containing your wheel.
Create an in-memory canvas containing your spike-indicator.
Rotate the canvas and draw the wheel on the main canvas.
Draw the indicator on the main canvas.
Change the rotation angle for the next loop.
Repeat, repeat, repeat using requestAnimationFrame.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var PI2=Math.PI*2;
var myData = [1,2,3,4,5,6,7,8,9,10,11,12];
var cx=150;
var cy=150;
var radius=150;
var wheel=document.createElement('canvas');
var wheelCtx=wheel.getContext('2d');
var indicator=document.createElement('canvas');
var indicatorCtx=indicator.getContext('2d');
var angle=PI2-PI2/4;
var myColor = [];
for(var i=0;i<myData.length;i++){ myColor.push(randomColor()); }
makeWheel();
makeIndicator();
requestAnimationFrame(animate);
function makeWheel(){
wheel.width=wheel.height=radius*2+2;
wheelCtx.lineWidth=1;
wheelCtx.font='24px verdana';
wheelCtx.textAlign='center';
wheelCtx.textBaseline='middle';
var cx=wheel.width/2;
var cy=wheel.height/2;
var sweepAngle=PI2/myData.length;
var startAngle=0;
for(var i=0;i<myData.length;i++){
// calc ending angle based on starting angle
var endAngle=startAngle+sweepAngle;
// draw the wedge
wheelCtx.beginPath();
wheelCtx.moveTo(cx,cy);
wheelCtx.arc(cx,cy,radius,startAngle,endAngle,false);
wheelCtx.closePath();
wheelCtx.fillStyle=myColor[i];
wheelCtx.strokeStyle='black';
wheelCtx.fill();
wheelCtx.stroke();
// draw the label
var midAngle=startAngle+(endAngle-startAngle)/2;
var labelRadius=radius*.85;
var x=cx+(labelRadius)*Math.cos(midAngle);
var y=cy+(labelRadius)*Math.sin(midAngle);
wheelCtx.fillStyle='gold';
wheelCtx.fillText(myData[i],x,y);
wheelCtx.strokeText(myData[i],x,y);
// increment angle
startAngle+=sweepAngle;
}
}
function makeIndicator(){
indicator.width=indicator.height=radius+radius/10;
indicatorCtx.font='18px verdana';
indicatorCtx.textAlign='center';
indicatorCtx.textBaseline='middle';
indicatorCtx.fillStyle='skyblue';
indicatorCtx.strokeStyle='blue';
indicatorCtx.lineWidth=1;
var cx=indicator.width/2;
var cy=indicator.height/2;
indicatorCtx.beginPath();
indicatorCtx.moveTo(cx-radius/8,cy);
indicatorCtx.lineTo(cx,cy-indicator.height/2);
indicatorCtx.lineTo(cx+radius/8,cy);
indicatorCtx.closePath();
indicatorCtx.fillStyle='skyblue'
indicatorCtx.fill();
indicatorCtx.stroke();
indicatorCtx.beginPath();
indicatorCtx.arc(cx,cy,radius/3,0,PI2);
indicatorCtx.closePath();
indicatorCtx.fill();
indicatorCtx.stroke();
indicatorCtx.fillStyle='blue';
indicatorCtx.fillText('Prizes',cx,cy);
}
function animate(time){
ctx.clearRect(0,0,cw,ch);
ctx.translate(cw/2,ch/2);
ctx.rotate(angle);
ctx.drawImage(wheel,-wheel.width/2,-wheel.height/2);
ctx.rotate(-angle);
ctx.translate(-cw/2,-ch/2);
ctx.drawImage(indicator,cw/2-indicator.width/2,ch/2-indicator.height/2)
angle+=PI2/360;
requestAnimationFrame(animate);
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<canvas id="canvas" width=400 height=300></canvas>
You can just put the "wheel" image on the website and just rotate it.
document.getElementById("TheImage").style.transform = "rotate("+YourAngle+"deg)";
Also you will need to put the "pointer" image on top of "wheel" image. (you will not rotate this one)
This is a fiddle written in 20 minutes, hope it helps.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
var lines = new Array();
lines[0] = new Array();
lines[0] = ["Prize 1","#000000"];
lines[1] = new Array();
lines[1] = ["Prize 2","#ffff00"];
lines[2] = new Array();
lines[2] = ["Prize 3","#ff00ff"];
lines[3] = new Array();
lines[3] = ["Prize 4","#00ffff"];
lines[4] = new Array();
lines[4] = ["Prize 5","#00ff00"];
var TO_RADIANS = Math.PI / 180;
var angle = 360 / lines.length; //to see how far apart the lines need to be
var angle_offset = 0; //this will determine the spinning
var angle_speed = 1; //degrees per cycle
var center_offset = 20; //the radius of your spinner in the middle
function animate() {
ctx.clearRect(0,0,canvas.width,canvas.height);
angle_offset+=angle_speed;
ctx.font="20px Verdana";
ctx.fillStyle="#000000";
for (i=0; i<lines.length; i++) {
ctx.fillStyle=lines[i][1];
ctx.save();
ctx.translate(canvas.width/2, canvas.height/2);
ctx.rotate((angle * i + angle_offset) * TO_RADIANS);
//Here you can also decorate with boxes and stuff
ctx.fillText(lines[i][0],center_offset,0);
ctx.restore();
}
requestAnimationFrame(animate);
}
animate();
<canvas id="canvas"></canvas>
I've been following various guides and have the base code up for a simple animation but for the life of me I cannot get the canvas to reset correctly. The clearRect() function is working perfectly but when I try to draw an arc again immediatly afterwards it draws the sum of all the paths again rather than just drawing the single segment of the circle.
Can someone tell me what I'm doing wrong here, I know it's a simple solution! In short I would like the test page below to produce a kind of spinning segment instead of just drawing a circle:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<span id="degrees_output" style="display:block;width:60px"></span>
<button onclick="continue_animation=false;">Stop</button>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var degrees = 0;
var continue_animation = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var output = document.getElementById('degrees_output');
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animate() {
// update
output.innerHTML = degrees;
var radians = (degrees / 180) * Math.PI;
if (degrees >= 360)
degrees = 0;
else
degrees += 1;
// clear
if (degrees % 20 == 0)
{
context.clearRect(0, 0, 578, 200);
}
context.beginPath();
// setup the line style
context.strokeStyle = '#fa00ff';
context.lineWidth = 5;
context.lineCap = 'round';
context.arc(50, 50, 20, 0, radians, false);
// colour the path
context.stroke();
context.closePath();
// request new frame
requestAnimFrame(function() {
if (continue_animation)
animate();
});
}
animate();
</script>
If you want a fixed length arc to sweep around your circle, you'll want to specify both the starting and ending angles in your context.arc like this:
context.arc(50, 50, 20, startRadians, radians, false);
and startRadians can just be any angle behind your "radians" value:
var startRadians= (degrees-45) * Math.PI/180;
and, Yes, you will need to clear the canvas (at least the previous arc) before drawing the arc in a new position:
context.clearRect(0,0,canvas.width,canvas.height);
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/VFhzX/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var degrees = 0;
var continue_animation = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var output = document.getElementById('degrees_output');
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animate() {
// update
output.innerHTML = degrees;
var radians = (degrees / 180) * Math.PI;
var startRadians= (degrees-45) * Math.PI/180;
if (degrees >= 360)
degrees = 0;
else
degrees += 1;
// clear
if (degrees % 20 == 0)
{
context.clearRect(0, 0, 578, 200);
}
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
// setup the line style
context.strokeStyle = '#fa00ff';
context.lineWidth = 5;
context.lineCap = 'round';
context.arc(50, 50, 20, startRadians, radians, false);
// colour the path
context.stroke();
context.closePath();
// request new frame
requestAnimFrame(function() {
if (continue_animation)
animate();
});
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<span id="degrees_output" style="display:block;width:60px"></span>
<button onclick="continue_animation=false;">Stop</button>
<canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>
I would like to display rotated camera video at a rate of 2 frames/second. The following code displays a 240 x 320 image rotated at 90 degrees. The image does not update unless I refresh the browser. The source that is changing is cam_1.jpg. It seems that once DrawImage has a src image, it does look for an update.
What have I not learned yet? Thank You for your time and expertise.
<title>CamDisplay</title></head><body>
<canvas height="320" width="240"></canvas>
<script type="text/javascript" charset="utf-8">
var cam = new Image;
window.onload = function(){
var c = document.getElementsByTagName('canvas')[0];
var ctx = c.getContext('2d');
setInterval(function(){
ctx.save();
ctx.clearRect( 0, 0, 240, 320 );
ctx.translate( 240, 0);
cam.src = 'cam_1.jpg?uniq='+Math.random();
ctx.rotate( 1.57);
ctx.drawImage( cam, 0, 0 );
ctx.restore();
},500);
};
</script>
</body>
</html>
the image is not getting time to load. try
var cam = new Image;
var c = document.getElementsByTagName('canvas')[0];
var ctx = c.getContext('2d');
cam.onload = function() {
ctx.save();
ctx.clearRect( 0, 0, 240, 320 );
ctx.translate( 240, 0);
ctx.rotate( 1.57);
ctx.drawImage( this, 0, 0 );
ctx.restore();
}
window.onload = function(){
setInterval(function(){
cam.src = 'cam_1.jpg?uniq='+Math.random();
},500);
}
How can I draw a rectangle with a gradient effect like the one pictured below using the HTML5 canvas element?
Edit: Thanks for all the feedback. Yes, I have already tried many methods. For example, can I use the createRadialGradient method as #Loktar suggests? Here is some sample code:
<html>
<head>
<title>test</title>
<script type="application/x-javascript">
function draw() {
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var grad1 = ctx.createRadialGradient(50, 50, 0, 50, 50, 50);
grad1.addColorStop(0, 'rgba(255, 252, 0, 1)');
grad1.addColorStop(1, 'rgba(68, 205, 37, 1)');
ctx.fillStyle = grad1;
ctx.fillRect(0, 0, 100, 100);
}
</script>
</head>
<body onload="draw();">
<div>
<canvas id="canvas" width="100" height="100"></canvas>
</div>
</body>
</html>
But the result is not quite what I want:
This should be done easily with a method like PathGradientBrush provided by GDI+.
I'm not sure is it possible with the HTML5 canvas element.
You could try to use a combination of linear gradient and clipping. Demo. Code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var outerColor = 'rgba(68,205,37,1)';
var innerColor = 'rgba(255,252,0,1)';
var w = 200;
var h = 50;
canvas.width = w;
canvas.height = h;
function gradient(dir) {
var grad = ctx.createLinearGradient(dir[0], dir[1], dir[2], dir[3]);
grad.addColorStop(0, outerColor);
grad.addColorStop(0.5, innerColor);
grad.addColorStop(1.0, outerColor);
return grad;
}
// idea: render background gradient and a clipped "bow"
function background() {
ctx.fillStyle = gradient([0, 0, 0, h]);
ctx.fillRect(0, 0, w, h);
}
function bow() {
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(w, h);
ctx.lineTo(w, 0);
ctx.lineTo(0, h);
ctx.clip();
ctx.fillStyle = gradient([0, 0, w, 0]);
ctx.fillRect(0, 0, w, h);
ctx.restore();
}
background();
bow();