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>
Related
Let's say I have an scanned paper with some black filled rectangles and I want to positionate all of them, getting their coordinates (X and Y) and their dimensions (Width and Height).
Is there any accurate algorithm which does what I need? I'm new to pixel processing with Javascript and Canvas and I need some help. Thanks in advance!
Identifying the x,y,width,height of all black rectangles involves these steps:
Use context.getImageData to get an array of all the r,g,b,a pixel information on the canvas.
Scan the pixel colors to find any one black pixel.
Find the bounding box of the black rectangle containing that one black pixel.
That bounding box will give you the x,y,width,height of one black rectangle.
Clear that black rectangle so that it is not found when searching for the next black rectangle.
Repeat step#1 until all the rectangles are identified.
Here's example code and a Demo: http://jsfiddle.net/m1erickson/3m0dL368/
<!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;}
#clips{border:1px solid blue; padding:5px;}
img{margin:3px;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw,ch;
// background definition
// OPTION: look at the top-left pixel and assume == background
// then set these vars automatically
var isTransparent=false;
var bkColor={r:255,g:255,b:255};
var bkFillColor="rgb("+bkColor.r+","+bkColor.g+","+bkColor.b+")";
cw=canvas.width;
ch=canvas.height;
ctx.fillStyle="white";
ctx.fillRect(0,0,canvas.width,canvas.height);
drawTestRect(30,30,50,50,"1");
drawTestRect(100,30,50,50,"2");
drawTestRect(170,30,50,50,"3");
function drawTestRect(x,y,w,h,label){
ctx.fillStyle="black";
ctx.fillRect(x,y,w,h);
ctx.fillStyle="white";
ctx.font="24px verdana";
ctx.fillText(label,x+10,y+25);
}
function clipBox(data){
var pos=findEdge(data);
if(!pos.valid){return;}
var bb=findBoundary(pos,data);
alert("Found target at "+bb.x+"/"+bb.y+", size: "+bb.width+"/"+bb.height);
clipToImage(bb.x,bb.y,bb.width,bb.height);
if(isTransparent){
// clear the clipped area
// plus a few pixels to clear any anti-aliasing
ctx.clearRect(bb.x-2,bb.y-2,bb.width+4,bb.height+4);
}else{
// fill the clipped area with the bkColor
// plus a few pixels to clear any anti-aliasing
ctx.fillStyle=bkFillColor;
ctx.fillRect(bb.x-2,bb.y-2,bb.width+4,bb.height+4);
}
}
function xyIsInImage(data,x,y){
// find the starting index of the r,g,b,a of pixel x,y
var start=(y*cw+x)*4;
if(isTransparent){
return(data[start+3]>25);
}else{
var r=data[start+0];
var g=data[start+1];
var b=data[start+2];
var a=data[start+3]; // pixel alpha (opacity)
var deltaR=Math.abs(bkColor.r-r);
var deltaG=Math.abs(bkColor.g-g);
var deltaB=Math.abs(bkColor.b-b);
return(!(deltaR<5 && deltaG<5 && deltaB<5 && a>25));
}
}
function findEdge(data){
for(var y=0;y<ch;y++){
for(var x=0;x<cw;x++){
if(xyIsInImage(data,x,y)){
return({x:x,y:y,valid:true});
}
}}
return({x:-100,y:-100,valid:false});
}
function findBoundary(pos,data){
var x0=x1=pos.x;
var y0=y1=pos.y;
while(y1<=ch && xyIsInImage(data,x1,y1)){y1++;}
var x2=x1;
var y2=y1-1;
while(x2<=cw && xyIsInImage(data,x2,y2)){x2++;}
return({x:x0,y:y0,width:x2-x0,height:y2-y0+1});
}
function drawLine(x1,y1,x2,y2){
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.strokeStyle="red";
ctx.lineWidth=0.50;
ctx.stroke();
}
function clipToImage(x,y,w,h){
// don't save anti-alias slivers
if(w<3 || h<3){ return; }
// save clipped area to an img element
var tempCanvas=document.createElement("canvas");
var tempCtx=tempCanvas.getContext("2d");
tempCanvas.width=w;
tempCanvas.height=h;
tempCtx.drawImage(canvas,x,y,w,h,0,0,w,h);
var image=new Image();
image.width=w;
image.height=h;
image.src=tempCanvas.toDataURL();
$("#clips").append(image);
}
$("#unbox").click(function(){
var imgData=ctx.getImageData(0,0,cw,ch);
var data=imgData.data;
clipBox(data);
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="unbox">Clip next sub-image</button><br>
<canvas id="canvas" width=300 height=150></canvas><br>
<h4>Below are images clipped from the canvas above.</h4><br>
<div id="clips"></div>
</body>
</html>
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>
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>
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>
I have to draw 3 images on the canvas and need to rotate 2 of the images.
The images are like
1. circular with a vertical straight line
2. just an horizontal line
3. Big circular image
I need to rotate the 1st 2 images in the center of the canvas.
var canvas = document.getElementById('NewImage');
var context = canvas.getContext('2d');
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight*0.7;
var imageObj = new Image();
var imageObj2 = new Image();
var imageObj3 = new Image();
imageObj.onload = function() {
context.save();
context.translate(imageObj.width/2,imageObj.height/2);
context.rotate(-10*Math.PI/180);
//context.translate(-imageObj.width/2,-imageObj.height/2);
context.drawImage(imageObj,-(imageObj.width/2),-(imageObj.height/2),context.canvas.width,context.canvas.height*0.85);
context.restore();
context.save();
context.globalCompositeOperation="source-over";
context.translate(imageObj2.width/2,imageObj2.height/2);
context.rotate(-10*Math.PI/180);
context.translate(-imageObj2.width/2,-imageObj2.height/2);
context.drawImage(imageObj2, x, y,context.canvas.width,6);
context.restore();
//context.rotate(10*Math.PI/180);
context.drawImage(imageObj3, 0, 0,context.canvas.width,context.canvas.height*0.9);
};
imageObj.src = 'canvas/inner_circle_blackline_vertical.png';
imageObj2.src = 'canvas/horizontal.png';
imageObj3.src = 'canvas/outer_circle.png';
When i try to rotate, the images are not rotating in center. when 1st 2 images rotates it has to look like "X" symbol.
How will i rotate in center of the canvas.
Thanks:)
As designed, your imageObj2 and imageObj3 will never load.
Here is a generic image loader that will load all your images and store them in an array called imgs[].
When all your images have fully loaded, the render() function will be called. That’s where you start drawing.
// This is an image loader
// When render() is called, all your images are fully loaded
var imgURLs = [
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs=[];
var imgCount=0;
pre_load();
function pre_load(){
for(var i=0;i<imgURLs.length;i++){
var img=new Image();
imgs.push(img);
img.onload=function(){
if(++imgCount>=imgs.length){
// images are now fully loaded
render();
}
}
img.src=imgURLs[i];
}
}
In render(), you just draw your images.
Since the same action (rotating an image) is done repeatedly, you can create a helper function to do the rotated drawing. Here the helper function is drawImageAtAngle.
// draw the rotated lines on the canvas
function render(){
var x=canvas.width/2;
var y=canvas.height/2;
drawImageAtAngle(imgs[0],x,y,-45);
drawImageAtAngle(imgs[2],x,y,45);
drawImageAtAngle(imgs[1],x,y,0);
}
Here the helper function that rotates a supplied image to a supplied angle:
function drawImageAtAngle(image,X,Y,degrees){
var radians=degrees*Math.PI/180;
var halfWidth=image.width/2;
var halfHeight=image.height/2;
ctx.beginPath();
ctx.save();
ctx.translate(X,Y);
ctx.rotate(radians);
ctx.drawImage(image,-halfWidth,-halfHeight);
ctx.restore();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/ZShWW/
<!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:10px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// This is an image loader
// When render() is called, all your images are fully loaded
var imgURLs = [
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs=[];
var imgCount=0;
pre_load();
function pre_load(){
for(var i=0;i<imgURLs.length;i++){
var img=new Image();
imgs.push(img);
img.onload=function(){
if(++imgCount>=imgs.length){
// images are now fully loaded
render();
}
}
img.src=imgURLs[i];
}
}
// draw the rotated lines on the canvas
function render(){
var x=canvas.width/2;
var y=canvas.height/2;
drawImageAtAngle(imgs[0],x,y,-45);
drawImageAtAngle(imgs[2],x,y,45);
drawImageAtAngle(imgs[1],x,y,0);
}
function drawImageAtAngle(image,X,Y,degrees){
var radians=degrees*Math.PI/180;
var halfWidth=image.width/2;
var halfHeight=image.height/2;
ctx.beginPath();
ctx.save();
ctx.translate(X,Y);
ctx.rotate(radians);
ctx.drawImage(image,-halfWidth,-halfHeight);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<p>This is the line image</p>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png">
<p>The line image rotated at center of canvas</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
To find the center of the canvas you have to use the dimensions of the canvas. In your code you are using the dimensions of the image. That is, this line:
context.translate(imageObj.width/2,imageObj.height/2);
should probably be:
context.translate(canvas.width/2,canvas.height/2);
That moves you to the center of the canvas. The rotation then occurs around that center. You are then drawing the image centered on the origin. That part looks correct.
You will then reverse the rotation and then the translation.