页面
<html>
<body>
<canvas id="canvas" width="800" height="800">
<%--浏览器不支持canvas 标签--%>
</canvas>
</body>
</html>
Js
获取画笔
function getCTX() {
let c = document.getElementById("canvas");
let ctx = c.getContext("2d");
ctx.clearRect(0,0,c.width,c.height);
return ctx;
}
画点示例
function drawPoint(point) {
let ctx = getCTX();
ctx.fillStyle = "#0000FF";
ctx.fillRect(point.x - 2, point.y - 2, 4, 4);
ctx.font = "16px bold 宋体";
ctx.fillText("(" + point.x + ", " + point.y + ")", point.x, point.y);
}
画路径(多条线)示例
function drawPath(path){
ctx.beginPath();
ctx.strokeStyle = "#0000FF";
for(var i = 0; i < path.length - 1; i++){
drawLine(ctx, points[path[i]], points[path[i+1]]);
}
}
function drawLine(ctx, a, b){
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.stroke();
}