Disegnare un rettangol usando il comando lineTo e cambiando colore alla linea ad ogni lato.
Il listato è il seguente:
<html>
<body>
<canvas id=”myCanvas” width=”300″ height=”150″ style=”border:1px solid #d3d3d3;”></canvas>
<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.beginPath();
ctx.strokeStyle=”blue”;
ctx.moveTo(20,20);
ctx.lineTo(150,20);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle=”red”;
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle=”yellow”;
ctx.moveTo(150,20);
ctx.lineTo(150,100);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle=”black”;
ctx.moveTo(20,100);
ctx.lineTo(150,100);
ctx.stroke();
</script>
</body>
</html>
Ed ecco il risultato grafico.