htmlcanvas

Draw a pin on Canvas using HTML5


I need to draw a pin like: http://www.clipartbest.com/clipart-9czEGGdRi using HTML5 on a Canvas.

Here's what I have: http://jsfiddle.net/u5jNR/

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = .9 * Math.PI;
var endAngle = 2.1 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = 'black';
context.stroke();


var radius = 20;

context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.stroke();

the problem I am having is I don't know how to extend the two ends.

Thanks in advance


Solution

  • Here's an example of using path commands to draw a pin.

    Assume you have an object defining the pin's x,y & color:

    var pin = { x:x, y:y, color:color };
    

    Then you can draw that pin like this:

    function drawPin(pin){
    
        ctx.save();
        ctx.translate(pin.x,pin.y);
    
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.bezierCurveTo(2,-10,-20,-25,0,-30);
        ctx.bezierCurveTo(20,-25,-2,-10,0,0);
        ctx.fillStyle=pin.color;
        ctx.fill();
        ctx.strokeStyle="black";
        ctx.lineWidth=1.5;
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(0,-21,3,0,Math.PI*2);
        ctx.closePath();
        ctx.fillStyle="black";
        ctx.fill();
    
        ctx.restore();
    }