자바 스크립트 객체를 사용의 이점은 이동해야하는 경우가 더 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();
}
을 다시 그릴 그릴 해당 개체를 사용할 수 있습니다, 당신은 단지) (객체의 획 속성을 변경하고 그릴 호출해야 다시 : 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>
012 : 여기
paths[0].stroke="orange";
paths[1].stroke="green";
draw();
는 코드와 바이올린입니다
어쩌면 함수에서 해당 작업을 저장? 따라서 일련의 기능을 사용할 수 있습니다. – Cristy
이러한 종류의 기능이 필요할 때마다 SVG 사용을 고려하십시오. – slebetman