PDF版 ePub版

# Ch4 多线条组成图形

## 绘制折线

<!DOCTYPE html>
<html lang="zh">
<meta charset="UTF-8">
<title>绘制折线</title>
<body>
<div id="canvas-warp">
<canvas id="canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">
你的浏览器居然不支持Canvas？！赶快换一个吧！！
</canvas>
</div>

<script>
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;
var context = canvas.getContext("2d");

context.moveTo(100,100);
context.lineTo(300,300);
context.lineTo(100,500);
context.lineWidth = 5;
context.strokeStyle = "#AA394C";
context.stroke();
}
</script>
</body>
</html>

## 绘制多条折线

<!DOCTYPE html>
<html lang="zh">
<meta charset="UTF-8">
<title>绘制折线</title>
<body>
<div id="canvas-warp">
<canvas id="canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">
你的浏览器居然不支持Canvas？！赶快换一个吧！！
</canvas>
</div>

<script>
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;
var context = canvas.getContext("2d");

context.moveTo(100,100);
context.lineTo(300,300);
context.lineTo(100,500);
context.lineWidth = 5;
context.strokeStyle = "red";
context.stroke();

context.moveTo(300,100);
context.lineTo(500,300);
context.lineTo(300,500);
context.lineWidth = 5;
context.strokeStyle = "blue";
context.stroke();

context.moveTo(500,100);
context.lineTo(700,300);
context.lineTo(500,500);
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
}
</script>
</body>
</html>

## 使用beginPath()开始绘制

<!DOCTYPE html>
<html lang="zh">
<meta charset="UTF-8">
<title>绘制折线</title>
<body>
<div id="canvas-warp">
<canvas id="canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">
你的浏览器居然不支持Canvas？！赶快换一个吧！！
</canvas>
</div>

<script>
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;
var context = canvas.getContext("2d");

context.beginPath();
context.moveTo(100,100);
context.lineTo(300,300);
context.lineTo(100,500);
context.lineWidth = 5;
context.strokeStyle = "red";
context.stroke();

context.beginPath();
context.moveTo(300,100);
context.lineTo(500,300);
context.lineTo(300,500);
context.lineWidth = 5;
context.strokeStyle = "blue";
context.stroke();

context.beginPath();
context.moveTo(500,100);
context.lineTo(700,300);
context.lineTo(500,500);
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
}
</script>
</body>
</html>