move the canvas image like Pendulum - javascript

i`m building html5 games like city blocs i want to move rob picture like Pendulum
the drwing function
function draw(){
ctx.save();
ctx.translate(20,0);
ctx.translate(box1.width/2,0);
ctx.rotate(val*(Math.PI/180));
ctx.drawImage(box1,box1.X,box1.Y);
ctx.restore();
}
now i have rotation method ready
i tried this to move it as i said
function boxPendolAnim(){
loop1 = setInterval(function(){
val = val -0.1;
},200);
setInterval(function(){
if (val <=-2) {
clearInterval(loop1);
setInterval(function(){
val = val +0.1;
},200);
};
},200);
}
but it work only once no more then stopped
i want function to move the picture like pendulum

In your code:
Just use 1 setInterval.
In the function executed by setInterval, increase the angle until it is at your desired maximum and then decrease the angle.
This is an example of an image in pendulum motion:
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/n9KrM/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var rotation=0; // start at horizontal
var direction=Math.PI/60; // 3 degrees change each loop
var box1=new Image();
box1.onload=function(){
setInterval(go,40);
}
box1.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";
function go(){
// set the new rotation
rotation+=direction;
if(rotation>Math.PI || rotation<0){
direction=-direction;
rotation+=direction;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
draw();
}
function draw(){
ctx.save();
ctx.translate(120,40);
ctx.rotate(rotation);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(40,0);
ctx.rect(40,-15,30,30);
ctx.stroke();
ctx.drawImage(box1,0,0,box1.width,box1.height,40,-15,30,30);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Related

Canvas size in HTML5

I have this code in my project, here is the link: http://jsfiddle.net/89wgk/
This is my code:
<canvas id="myCanvas" width="188" height="200"></canvas>
var rectWidth = 110;
var rectHeight = 110;
var rectX = 10;
var rectY = 25;
When I put the mouse in curved rectangle starts the shadow, but I want that to happen when I put the mouse over the reeds (rectangle) and not within the canvas.
I wonder how do I run the shadow so when I move the mouse over the rectangle?
Here is how I would do it:
create a function that draws the arc shape because it must be redrawn often
listen for mouseMove events on the canvas
test whether the mouse is inside the arc with context.isPointInside(mouseX,mouseY)
redraw the arc with/without the shadow based on if the mouse is inside the arc
Have Fun!
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/64BHx/
<!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 canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var w = 110;
var h = 110;
var x = 10;
var y = 25;
var isShadowed=false;
context.strokeStyle="#FF2A2A";
context.shadowBlur = 20;
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.globalAlpha=.250;
context.strokeRect(x,y,w,h);
context.globalAlpha=1.00;
function draw(){
// clear the canvas
context.clearRect(0,0,canvas.width,canvas.height);
// save the context state
context.save();
// set/clear the shadow based on isShadowed
context.shadowColor= isShadowed ? '#7FD4FF' : "#FFFFFF";
// draw the arc shape
context.beginPath();
context.moveTo(x,y);
context.quadraticCurveTo(x+w-2,y+2,x+w,y+h);
context.lineTo(x+w-35,y+h);
context.quadraticCurveTo(x+w-2-35,y+2+35,x,y+35);
context.lineTo(x,y);
context.fillStyle="red";
context.fill();
context.stroke();
// restore the context state
context.restore();
}
// testing: display if mouse is in/out of arc shape
var $status=$("#status");
// listen for mousemove events
$("#canvas").mousemove(function(e){handleMouseMove(e);});
// handle mousemove events
function handleMouseMove(e){
// we alone are using mousemove events
e.preventDefault();
// get current mouse X/Y
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// hit test if mouse is inside the arc shape
var isInside=context.isPointInPath(mouseX,mouseY);
$status.text("Is mouse inside: "+isInside);
// don't redraw unless needed
if(isInside && isShadowed){return;}
if(!isInside && !isShadowed){return;}
// change the shadow and redraw
isShadowed=isInside;
draw();
}
// start by drawing the unshadowed arc
draw();
}); // end $(function(){});
</script>
</head>
<body>
<p id="status">Status</p><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

undo the selected shape on the canvas

I would like to a particular shape on the canvas.
I have implemented a canvas on which we can draw shapes like rectangle, circle, line, ellipse and so on using mouse events.
I have created a drop down list with all the shapes that I am drawing on the canvas.
The drop down list consists of shapes like circle, rectangle, parallelogram, ellipse, circle...
Now what I want is, for example, think that I have drawn 2 rectangles and 2 circles. When I select circle shape from the drop down list and click undo button it should undo only the circles and if I select the rectangle shape from the drop down list and click on undo button it should undo only the rectangle shapes not the other shapes
the code that i am using for undo in the canvas is :
function cPush()
{
canvas = document.getElementById("drawingCanvas");
context = canvas.getContext("2d");
cStep++;
if (cStep < cPushArray.length)
{
cPushArray.length = cStep;
}
cPushArray.push(document.getElementById('drawingCanvas').toDataURL());
}
function cUndo()
{
canvas = document.getElementById("drawingCanvas");
context = canvas.getContext("2d");
context.clearRect(0,0,canvas.width, canvas.height);
if (cStep > 0)
{
cStep--;
var canvasPic = new Image();
canvasPic.src = cPushArray[cStep];
context.drawImage(canvasPic, 0, 0);
}
}
How to "undo" (remove a specified shape and redraw the remaining shapes)
Demo: http://jsfiddle.net/m1erickson/9pTJ2/
Create an array to hold all your shape definitions:
var drawings=[];
Add shapes to the array:
function addShape(shapename,color){
drawings.push({
shape:shapename,
color:color
});
drawAll();
}
To "undo", remove all elements of a specified shape from the array:
function undoShape(shapename){
var i=drawings.length-1;
while(i>=0){
if(drawings[i].shape==shapename){
drawings.splice(i,1);
}
i--;
}
drawAll();
}
Here is code:
[ props to #enhzflep for suggesting the method ]
<!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 canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=1;
var shapeWidth=30;
var shapeHeight=30;
var spacer=5;
var drawings=[];
function addShape(shapename,color){
drawings.push({
shape:shapename,
color:color
});
drawAll();
}
function undoShape(shapename){
var i=drawings.length-1;
while(i>=0){
if(drawings[i].shape==shapename){
drawings.splice(i,1);
}
i--;
}
drawAll();
}
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<drawings.length;i++){
var drawing=drawings[i];
var x=i*shapeWidth;
var y=50;
switch(drawing.shape){
case "rectangle":
drawRectangle(x,y,drawing.color);
break;
case "circle":
drawCircle(x,y,drawing.color);
break;
}
}
}
function drawContainer(x,y){
ctx.strokeStyle="lightgray";
ctx.strokeRect(x,y,shapeWidth,shapeHeight);
}
function drawRectangle(x,y,color){
drawContainer(x,y);
ctx.fillStyle=color;
ctx.fillRect(x+spacer,y+spacer,shapeWidth-2*spacer,shapeHeight-2*spacer);
}
function drawCircle(x,y,color){
drawContainer(x,y);
ctx.beginPath();
ctx.arc(x+shapeWidth/2,y+shapeHeight/2,shapeWidth/2-spacer,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=color;
ctx.fill();
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
$("#rect").click(function(){
addShape("rectangle",randomColor());
});
$("#circle").click(function(){
addShape("circle",randomColor());
});
$("#norect").click(function(){
undoShape("rectangle");
});
$("#nocircle").click(function(){
undoShape("circle");
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="rect">Add Rect</button>
<button id="circle">Add Circle</button>
<button id="norect">Erase Rects</button>
<button id="nocircle">Erase Circles</button>
<canvas id="tools" width=300 height=40></canvas><br>
<canvas id="erasers" width=300 height=40></canvas><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Show converted mouse coordinates of an element with javascript

I'd like to show a mouse tooltip like this:
with a coordinate system relative to its image.
Whenever the mouse is hovered over one of the 75x75 cells, the position is displayed in text. I can only show the mouse's raw coordinates, but can't figure out the math to display it like it is in the picture.
I'm open to HTML5 implementations as well.
Here’s how to convert mouse coordinates to cell coordinates and display a tooltip
This math calculates which 75x75 cell your mouse is inside:
var col=parseInt(mouseX/75);
var row=parseInt(mouseY/75);
And here is the math to calculate a tip rectangle in the upper-right of that cell:
var tipX=tipCol*75+75-tipWidth;
var tipY=tipRow*75;
You can use canvas to draw the tip inside the cell at your calculated coordinates:
function tip(x,y){
var tipX=tipCol*75+75-tipWidth;
var tipY=tipRow*75;
ctx.beginPath();
ctx.rect(tipX,tipY,tipWidth,tipHeight);
ctx.fillStyle="ivory";
ctx.fill();
ctx.fillStyle="blue";
ctx.fillText(tipCol+","+tipRow,tipX+2,tipY+17);
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/9V5QK/
<!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; padding:25px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var tipWidth=35;
var tipHeight=22;
var tipRow;
var tipCol;
ctx.font="14pt verdana";
draw();
function draw(){
// you would just draw your image here
// ctx.drawImage(0,0,image.width,image.height);
// but for illustration, this just recreates your image
ctx.beginPath();
ctx.rect(0,0,375,225);
for(var x=1;x<5;x++){ ctx.moveTo(x*75,0); ctx.lineTo(x*75,canvas.height); }
for(var y=1;y<3;y++){ ctx.moveTo(0,y*75); ctx.lineTo(canvas.width,y*75); }
ctx.fillStyle="black";
ctx.fill();
ctx.strokeStyle="gray";
ctx.lineWidth=2;
ctx.stroke();
}
function tip(x,y){
var tipX=tipCol*75+75-tipWidth;
var tipY=tipRow*75;
ctx.beginPath();
ctx.rect(tipX,tipY,tipWidth,tipHeight);
ctx.fillStyle="ivory";
ctx.fill();
ctx.fillStyle="blue";
ctx.fillText(tipCol+","+tipRow,tipX+2,tipY+17);
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#movelog").html("Move: "+ mouseX + " / " + mouseY);
// Put your mousemove stuff here
var col=parseInt(mouseX/75);
var row=parseInt(mouseY/75);
if(!(row==tipRow && col==tipCol)){
tipCol=col;
tipRow=row;
draw();
tip();
}
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Move mouse over grid to display current cell</p>
<p id="movelog">Move</p>
<canvas id="canvas" width=375 height=225></canvas>
</body>
</html>

Moving an object around on dynamic canvas

There are plenty of questions about how to move objects around in the first place, but this is different: suppose that I (obviously) want my object to go "in front" of the background, and that my background is being changed/generated all the time. Therefore, when I move the object from one place to another, I want what would have been generated if the object wasn't blocking it to appear where it was before. How should I handle this? Should I keep a record of "what would have been generated" where the object is and plop it on when it moves, or is there a less annoying way to get around this?
Canvas has a drawing setting to do exactly what you want !
You can use the canvas context's globalCompositeOperation.
This allows you to move your "front" image on top of your "background-changing" image.
Here is some code and a Fiddle: http://jsfiddle.net/m1erickson/TrXB4/
<!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; background-color:black; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var sun = new Image();
var moon = new Image();
var earth = new Image();
function init(){
sun.src = 'http://cdn-img.easyicon.cn/png/36/3642.png';
moon.src = 'http://openclipart.org/people/purzen/purzen_A_cartoon_moon_rocket.svg';
earth.src = 'http://iconbug.com/data/26/256/e5b23e861bc9979da6c3d03b75862b7e.png';
setInterval(draw,100);
}
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
ctx.clearRect(0,0,350,350); // clear canvas
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);
// Earth
var time = new Date();
ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
ctx.translate(105,0);
ctx.fillRect(0,-12,50,24); // Shadow
ctx.drawImage(earth,-12,-12,48,48);
// Moon
ctx.save();
ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
ctx.translate(0,28.5);
ctx.drawImage(moon,-3.5,-3.5,16,32);
ctx.restore();
ctx.restore();
ctx.beginPath();
ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
ctx.stroke();
ctx.drawImage(sun,100,100,96,96);
}
init();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

How to make a needle image to rotate from 180 degree to 0, half of 360 degree

<!DOCTYPE html>
<html>
<head>
<title>Canvas Cog</title>
<script type="text/javascript">
var cog = new Image();
function init() {
cog.src = 'needle.png'; // Set source path
setInterval(draw,100);
}
var rotation = 0;
function draw(){
var ctx = document.getElementById('myCanvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
ctx.save();
ctx.clearRect(0,0,500,500);
ctx.translate(200,180); // to get it in the origin
rotation +=1;
ctx.rotate(rotation*Math.PI/180); //rotate in origin
ctx.translate(0,-90); //put it back
ctx.drawImage(cog,(-13.5),(-13.5),48,111);
ctx.restore();
}
init();
</script>
</head>
<body>
<canvas width="500" height="500" id="myCanvas"></canvas>
</body>
</html>
using HTML5 Canvas - rotate image about arbitrary point

Categories

Resources