Canvas How to - Cut ring shape with mouse








Question

We would like to know how to cut ring shape with mouse.

Answer


<!-- w w  w  .  jav a 2  s  .c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var circ = Math.PI * 2;
var quart = Math.PI / 2;
var w = 200;
var h = 200;
var strokeSize = 40; 
var radius = 100;
function drawShape(percent){
    ctx.beginPath();      
    ctx.arc(w/2, h/2,radius-strokeSize/2,-(quart),((circ) * percent) - quart,false);
    ctx.strokeStyle = "#3B5DBA";
    ctx.lineCap = 'butt';
    ctx.lineWidth = strokeSize;
    ctx.stroke();
}
drawShape(1);
canvas.addEventListener('click', function(e){
    var x = e.pageX - canvas.offsetLeft - w/2,
        y = e.pageY - canvas.offsetTop - h/2,
        mAngle = Math.atan2(y, x);
    if (mAngle > -1 * Math.PI && mAngle < -0.5 * Math.PI) {
        mAngle = 2 * Math.PI + mAngle;
    }
    var percentage = (mAngle + Math.PI / 2) / 2 * Math.PI * 10;
    ctx.clearRect(0, 0, w, h);
    drawShape(percentage/100);
});
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="200" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: