Draw rectangle and triangle - Javascript Canvas

Javascript examples for Canvas:Rectangle

Description

Draw rectangle and triangle

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>
#canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){//  w ww . ja v  a2 s.co m
es to canvas and context
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var path1={lineWidth:1, stroke:"blue", points:[]};
    var path2={lineWidth:4, stroke:"red", points:[]};

    var paths=[];
    paths.push(path1);
    paths.push(path2);
    // build test path1
    newPoint(25,25,path1);
    newPoint(100,50,path1);
    newPoint(50,75,path1);
    newPoint(25,25,path1);

    newPoint(200,100,path2);
    newPoint(250,100,path2);
    newPoint(250,200,path2);
    newPoint(200,200,path2);
    newPoint(200,100,path2);

    draw();

    function newPoint(x,y,path){
        path.points.push({x:x,y:y});
    }
    function draw(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(p=0;p<paths.length;p++){

            var path=paths[p];

            ctx.beginPath();

            ctx.moveTo(path.points[0].x,path.points[0].y);

            for(pt=1;pt<path.points.length;pt++){
                var point=path.points[pt];
                ctx.lineTo(point.x,point.y);
            }

            ctx.strokeStyle=path.stroke;
            ctx.lineWidth=path.lineWidth;

            ctx.stroke();
        }
    }

    $("#recolor").click(function(){
        paths[0].stroke="orange";
        paths[1].stroke="green";
        draw();
    });
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <button id="recolor">Recolor</button>
      <br> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials