您可以将绘制路径所需的所有数据序列化为 javascript 对象
使用 javascript 对象的好处是,如果您需要将路径移动到不同的位置(例如回到服务器),可以进一步将对象序列化为 JSON。
var path1={
lineWidth:1,
stroke:"blue",
points:[{x:10,y:10},{x:100,y:50},{x:30,y:200}]
};
然后您可以使用该对象来绘制/重绘该路径
function draw(path){
// beginPath
ctx.beginPath();
// move to the beginning point of this path
ctx.moveTo(path.points[0].x,path.points[0].y);
// draw lines to each point on the path
for(pt=1;pt<path.points.length;pt++){
var point=path.points[pt];
ctx.lineTo(point.x,point.y);
}
// set the path styles (color & linewidth)
ctx.strokeStyle=path.stroke;
ctx.lineWidth=path.lineWidth;
// stroke this path
ctx.stroke();
}
要更改路径的颜色,您只需更改对象的 stroke 属性并再次调用 draw():
paths[0].stroke="orange";
paths[1].stroke="green";
draw();
这是代码和小提琴:http: //jsfiddle.net/m1erickson/McZrH/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
// get references to canvas and context
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// serialize paths to a javascript objects
var path1={lineWidth:1, stroke:"blue", points:[]};
var path2={lineWidth:4, stroke:"red", points:[]};
// save the paths to an array
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);
// build test path2
newPoint(200,100,path2);
newPoint(250,100,path2);
newPoint(250,200,path2);
newPoint(200,200,path2);
newPoint(200,100,path2);
// draw the paths defined in the paths array
draw();
// add a new point to a path
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++){
// get a path definition
var path=paths[p];
// beginPath
ctx.beginPath();
// move to the beginning point of this path
ctx.moveTo(path.points[0].x,path.points[0].y);
// draw lines to each point on the path
for(pt=1;pt<path.points.length;pt++){
var point=path.points[pt];
ctx.lineTo(point.x,point.y);
}
// set the path styles (color & linewidth)
ctx.strokeStyle=path.stroke;
ctx.lineWidth=path.lineWidth;
// stroke this path
ctx.stroke();
}
}
// test
// change the stroke color on each path
$("#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>