A Demo: http://jsfiddle.net/m1erickson/LVgwV/
You can use the context.arc
command to draw your pie wedge.
Listen for mouse events and in mousedown set the beginning angle of the wedge:
function handleMouseDown(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
var dx=mouseX-cx;
var dy=mouseY-cy;
begin=Math.atan2(dy,dx);
isDown=true;
}
In mousemove you can set your ending angle of the wedge:
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
var dx=mouseX-cx;
var dy=mouseY-cy;
end=Math.atan2(dy,dx);
draw();
}
Example code:
<!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.strokeStyle="lightgray";
ctx.lineWidth=3;
ctx.fillStyle="skyblue";
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var isDown=false;
var startX;
var startY;
var cx=150;
var cy=150;
var begin,end;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(cx,cy);
ctx.arc(cx,cy,75,begin,end);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function handleMouseDown(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
var dx=mouseX-cx;
var dy=mouseY-cy;
begin=Math.atan2(dy,dx);
isDown=true;
}
function handleMouseUp(e){
e.preventDefault();
isDown=false;
}
function handleMouseOut(e){
e.preventDefault();
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
var dx=mouseX-cx;
var dy=mouseY-cy;
end=Math.atan2(dy,dx);
draw();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag on canvas to create pie-wedge.</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>