Search code examples
htmlcanvashtml5-canvasjcanvas

Draw and plot Square dynamically Using HTML canvas


I need to draw this diagram given below using html canvas.Can anyone help me.

http://1.bp.blogspot.com/-em2abcEg5nU/Ts_c3cNtfMI/AAAAAAAAABU/eQWc6SJtD0M/s1600/t31.jpg


Solution

  • First get access to the canvas:

    var can=document.getElementById('canvas1')
    

    Now you need a context to perform the drawing functions:

    var pen=can.getContext('2d')
    

    To draw a line do the following:

    pen.beginPath()
    pen.moveTo(0,0)
    pen.lineTo(50,50)
    pen.closePath()
    pen.strokeStyle=rgb(255,0,0)
    pen.stroke()
    

    To fill a path (like a triangle) do the following:

    pen.beginPath()
    pen.moveTo(0,0)
    pen.lineTo(50,50)
    pen.lineTo(0,50)
    pen.closePath()
    pen.fillStyle=rgb(255,0,0)
    pen.fill()