undo the selected shape on the canvas - javascript

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>

Related

Find all black rectangles in canvas

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>

Moving canvas shapes with mouse

After pressing a button, I'd like to draw a circle at the tip of the mouse pointer on a canvas and then place it when the user clicks again. Here's what I've got so far:
$("#button").click(function(e){
var canvas = document.getElementById('MyCanvas');
var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
console.log(message);
var nodehandle = document.getElementById('circle');
if(mousePos.x && mousePos.y) {
nodehandle.x = mousePos.x;
nodehandle.y = mousePos.y;
flag = 1;
}
}, false);
});
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
My problem is that when I draw a circle like this:
function drawCircle(mouseX, mouseY){
var c = document.getElementById("grid");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,5,0,2*Math.PI);
ctx.stroke();
}
I don't know how to select that circle (the getElementById('circle') returns null even if I add ctx.id='circle' to the drawCircle function). I'm also going to need to erase and redraw the circle each time the mouse moves, and I'm sure there's a nice way to do that but I'm not aware of it.
Anything you draw on the canvas--like circles, are just like dried paint on the canvas.
Your circles cannot be selected or moved like html elements.
To move a circle you must clear the canvas and redraw the circle at a different location.
It's convenient to store info about the circle in an object.
var circle1 = { centerX:100, centerY=100, radius=20 }
And you can draw circle1 using that info:
ctx.beginPath();
ctx.arc(circle1.centerX, circle1.centerY, circle1.radius, 0,Math.PI*2);
ctx.closePath();
ctx.fill();
For more than 1 circle you can create a circles array and put each circle object into that array
var circles=[];
circles.push(circle1);
Then to "move" a circle, just change the object's centerX/centerY to the mouse position and redraw all the circles on the canvas.
circle1.centerX=mouseX;
circle1.centerY=mouseY;
// Clear the canvas and redraw all circles
// The "moved" circle will be redrawn at its new position
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<circles.length;i++){
var c=circles[i];
ctx.beginPath();
ctx.arc(c.centerX,c.centerY,c.radius,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=c.color;
ctx.fill();
}
}
You can use Html radio buttons to determine which action a mouse-click will do:
Create a new circle at the mouse position, or
Select the circle under the mouse position, or
"Move" the currently selected circle
Here's example code and a Demo: http://jsfiddle.net/m1erickson/CEB7T/
<!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(){
// get references to the canvas and its context
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
// get the canvas position on the page
// used to get mouse position
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
ctx.lineWidth=3;
// save info about each circle in an object
var circles=[];
var selectedCircle=-1;
// the html radio buttons indicating what action to do upon mousedown
var $create=$("#rCreate")[0];
var $select=$("#rSelect")[0];
var $move=$("#rMove")[0];
// draw all circles[]
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<circles.length;i++){
var c=circles[i];
ctx.beginPath();
ctx.arc(c.cx,c.cy,c.radius,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=c.color;
ctx.fill();
// if this is the selected circle, highlight it
if(selectedCircle==i){
ctx.strokeStyle="red";
ctx.stroke();
}
}
}
function handleMouseDown(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
if($create.checked){
// create a new circle a the mouse position and select it
circles.push({cx:mouseX,cy:mouseY,radius:10,color:randomColor()});
selectedCircle=circles.length-1;
}
if($select.checked){
// unselect any selected circle
selectedCircle=-1;
// iterate circles[] and select a circle under the mouse
for(var i=0;i<circles.length;i++){
var c=circles[i];
var dx=mouseX-c.cx;
var dy=mouseY-c.cy;
var rr=c.radius*c.radius;
if(dx*dx+dy*dy<rr){ selectedCircle=i; }
}
}
if($move.checked && selectedCircle>=0){
// move the selected circle to the mouse position
var c=circles[selectedCircle];
c.cx=mouseX;
c.cy=mouseY;
}
// redraw all circles
drawAll();
}
// return a random color
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
// handle mousedown events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<input type="radio" name="grp1" id="rCreate" checked>Click will create a new circle.<br>
<input type="radio" name="grp1" id="rSelect">Click will select an existing circle.<br>
<input type="radio" name="grp1" id="rMove">Click will move selected circle.<br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

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>

Javascript paint Canvas, need help re-locating buttons?

Hi i'm having trouble getting my paint canvas buttons that change the colours of the paint brush to move beside the canvas.
It seems to be stuck at the tope left hand corner of the webpage unfortunately and i'm struggling trying to re-locate it. And suggestions would be very helpful. Thank you.
Here is some of my code that should give you an idea of what im talking about.
var brush = 10;
function changeColour(colour)
{
g.fillStyle = colour;
}
function clearCanvas()
{
g.clearRect(0, 0, canvas.width, canvas.height);
}
var mouseIsDown = false;
function down(e)
{
mouseIsDown = true;
/*e.originalEvent.preventDefault();*/
}
function up(e)
{
mouseIsDown = false;
}
function changeBrushSize(symbol)
{
if(symbol =='+')
{
brush = brush + 2;
}
else if (symbol == '-')
{
brush = brush - 2;
}
}
function move(e)
{
var container = document.getElementById('container');
//g.clearRect(0, 0, canvas.width, canvas.height);
//g.fillRect(e.x - 5, e.y - 5, 100, 100);
if((e.button == 0) && (mouseIsDown))
{
g.beginPath();
document.onselectstart = function(){ return false; }
//g.fillStyle = "red";
g.arc((e.x - container.offsetLeft) - brush, (e.y - container.offsetTop) - brush, brush, 0, Math.PI * 2);
g.fill();
g.closePath();
}
}
</script>
</head>
<body>
<div id="container">
<canvas id = "paintCanvas" width = "500" height = "500">
Your browser does not support the HTML5 <canvas> tag.
</canvas>
</div>
<button onclick ="clearCanvas()">Clear Canvas</button></br>
<button onclick ="changeColour('red')">Red</button>
<button onclick ="changeColour('green')">Green</button>
<button onclick ="changeColour('blue')">Blue</button>
<button onclick ="changeColour('yellow')">Yellow</button>
<button onclick ="changeColour('orange')">Orange</button>
<button onclick ="changeColour('brown')">Brown</button>
<button onclick ="changeColour('purple')">Purple</button></br>
<button onclick ="changeBrushSize('+')">Bigger Brush</button>
<button onclick ="changeBrushSize('-')">Smaller Brush</button>
</body>
You might let the user select their colors and other tools from a second "tools" canvas
Then position the "tools" canvas before the "drawing" canvas.
<canvas id="toolsCanvas"></canvas><br>
<canvas id="drawingCanvas"></canvas>
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/y5xu7/
<!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: white; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("drawingCanvas");
var context=canvas.getContext("2d");
var tools=document.getElementById("toolsCanvas");
var ctx=tools.getContext("2d");
var canvasOffset=$("#toolsCanvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var colors=['Red','Green','Blue','Yellow','Orange','Brown','Purple']
var lightcolors="Yellow|White";
var colorPickerWidth=25;
// draw the color picker
tools.width=colors.length*colorPickerWidth;
for(var i=0;i<colors.length;i++){
ctx.fillStyle=colors[i];
ctx.fillRect(i*colorPickerWidth,0,colorPickerWidth,25);
}
// called when the user clicks and picks a color
function handleMouseDown(e){
console.log("down");
var x=parseInt(e.clientX-offsetX);
var color=colors[parseInt(x/colorPickerWidth)];
ctx.save();
ctx.fillStyle=color;
ctx.fillRect(0,28,tools.width,25);
ctx.fillStyle="white";
if(lightcolors.indexOf(color)>-1){ctx.fillStyle="black";}
ctx.font="16px verdana";
ctx.fillText("Selected: "+color,10,45);
ctx.restore();
context.clearRect(0,0,canvas.width,canvas.height);
context.fillStyle=color;
context.font="14px arial";
context.fillText("fillStyle==your selected color",30,100);
}
$("#toolsCanvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="toolsCanvas" width=300 height=53></canvas><br>
<canvas id="drawingCanvas" 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>

Categories

Resources