2013-10-19 3 views
5

HTML5 캔버스를 사용할 때 특정 경로를 javascript 변수/배열에 저장 한 다음 나중에 조작 할 수 있습니까? 여기에 내가 지금까지 뭘하는지입니다 :HTML5 캔버스 : 개별 경로 조작

    ctx.beginPath(); 
         ctx.moveTo(lastX,lastY); 
         ctx.lineTo(x,y); 
         ctx.lineWidth = s*2; 
         ctx.stroke(); 
        ctx.closePath(); 

을 지금, 나는이 필요로하는 것은, 시간에, 배열이 경로를 저장 할 수있다. 그런 다음 나중에 어레이의 모든 경로의 색상을 변경하고 되돌릴 수 있어야합니다. (분명히이 작업을 수행하는 방법을 알지 못합니다.)

+0

어쩌면 함수에서 해당 작업을 저장? 따라서 일련의 기능을 사용할 수 있습니다. – Cristy

+0

이러한 종류의 기능이 필요할 때마다 SVG 사용을 고려하십시오. – slebetman

답변

0

캔버스에서 캔버스보기를 지우거나 다시 그리지 않고 변경할 수는 없습니다. 따라서 캔버스를 그리는 함수를 만들어야합니다. 배열에서 라인 위치를 저장합니다. 함수에서 배열을 반복하면서이를 추가합니다. 분명히 언제든지 캔버스를 다시 그릴 수 있습니다. 일반적으로 이벤트 리스너 또는 타이밍 이벤트를 설정합니다.

0

짧은 대답 : 할 수 없습니다. Canvas2D API에 대한 다음 초안에 있지만 (http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas/#path-objects 참조) 아직 지원되지 않습니다.

길게 대답 할 수는 없지만 경로를 나타내는 개체를 작성하고 draw(canvas) 함수를 사용하면 선택한 색상과 채우기 속성을 사용하여 캔버스에 그려집니다. 예를 들면 : 당신은 자바 스크립트 객체로 경로를 그리는 데 필요한 모든 데이터를 직렬화 할 수

var Path = function() { 
    this.instructions = []; 
} 
Path.prototype = { 
    instructions: [], 
    moveTo: function(x,y) { 
    instructions.push({ 
     type: "moveTo", 
     arguments: [x,y] 
    }); 
    } 
    ... 
    draw: function(canvas) { 
    var ctx = canvas.getContext("2d"); 
    ctx.beginPath(); 
    this.instructions.forEach(function(i) { 
     ctx[i.type].apply(i.arguments); 
    }); 
    ctx.closePath(); 
    } 
} 
+0

그게 효과가있어, 정확히 어떻게 가야하지? 대답을 편집하려면 –

+0

답변 됨. –

+0

'Path'라는 객체를 미래의 경로를 위해 예약 된 것으로 호출하는 것에 조심하십시오. – K3N

2

자바 스크립트 객체를 사용의 이점은 이동해야하는 경우가 더 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(); 

는 코드와 바이올린입니다

2

새로운 path2D 개체를 사용할 수있는 것처럼 보입니다.

새로운 Path2D API (Firefox 31 이상에서 사용 가능)를 사용하면 패스를 저장할 수 있으므로 캔버스 그리기 코드를 단순화하고 빠르게 실행할 수 있습니다.

new Path2D();  // empty path object 
new Path2D(path); // copy from another path 
new Path2D(d); // path from from SVG path data 

, 구축 SVG 경로 데이터를 얻어 특히 유용 번째 버전 : 생성자는 클래스 Path2D 오브젝트를 작성하기위한 세 가지 방법을 제공한다. 당신은 지금뿐만 아니라 캔버스에 직접 같은 모양을 그립니다 SVG 경로를 다시 사용할 수 있습니다

var p = new Path2D("M10 10 h 80 v 80 h -80 Z"); 

정보 Mozilla official site에서 가져옵니다.

+0

감사합니다. –

0

이 도움이 될 수 있습니다 : 그것은 당신이 함수에 의해 해석하고, 작업이 수행되는 문자와 숫자로 구성된 문자열을 사용할 수있는 기능입니다

http://www.rgraph.net/blog/2015/september/svg-style-paths-for-canvas-with-the-rgraph-path-function.html

. 이제 경로는 SVG 경로와 마찬가지로 문자열이 될 수 있으며 데이터베이스를 돌아 다니거나 데이터베이스에 저장하는 것이 훨씬 쉽습니다.

그래서 사각형을 그릴 수있는 경로는 다음과 같습니다

B r을 의미 빨간색

F 5 5 100 100 :

b: beginPath() 
r: rect() 
f: fill()