2016-06-01 2 views
0

사용자가 그리려는 캔버스 크기를 선택할 수있는 페이지를 만들려고합니다.동일한 페이지에서 여러 캔버스에 canvas.getContext ("2d") 사용하기

이렇게하려면 크기가 다른 3 개의 캔버스가있는 페이지를 만들었고 각각의 버튼이 하나 있습니다. CSS에서 모든 캔버스를 숨긴 다음 jQuery를 사용하여 관련 버튼을 클릭 할 때 캔버스를 표시했습니다. 문제는 그게 내 HTML 문서의 첫 번째 캔버스를 제외한 모든 캔버스에 실제로 그릴 수있는 능력을 상실했다는 것입니다.

HTML

<canvas width="400" height="250" class="small"></canvas> 
<canvas width="600" height="400" class="medium"></canvas> 
<canvas width="1000" height="800" class="large"></canvas> 

JS

var context = $canvas[0].getContext("2d"); 

$canvas.mousedown(function(e){ 
    lastEvent = e; 
    mouseDown = true; 
}).mousemove(function(e){ 
    //Draw lines 
    if(mouseDown) { 
    context.beginPath(); 
    context.moveTo(lastEvent.offsetX, lastEvent.offsetY); 
    context.lineTo(e.offsetX, e.offsetY); 
    context.strokeStyle = color; 
    context.stroke(); 
    lastEvent = e; 
    } 
}).mouseup(function(){ 
    mouseDown = false; 
}).mouseleave(function(){ 
    $canvas.mouseup(); 
}); 

그 .getContext 문자열로 전화 3 캔버스를 선택하는 방법이 있나요 : 나는 문제가이 코드로 의심? Full code in case it's useful

+0

같은 것을 시도해야한다? –

+0

옵션을 사용하여 하나의 캔버스 크기 만 설정하면됩니다. 도면은 점을 기록하여 복제 할 수 있습니다. 3x 캔버스를 사용하면 필요한 것보다 훨씬 많은 메모리를 소비하므로 드로잉은 약 3 배 느려집니다. – K3N

답변

0

당신은 여러 캔버스에 대해 하나의 컨텍스트를 원하는

var tab = [$canvas[0].getContext("2d"), $canvas[1].getContext("2d"), $canvas[2].getContext("2d")] 
var lastEvent = null; 
var mouseDown = false; 

canvasParent.mousedown(function(e) 
{ 
    lastEvent = e; 
    mouseDown = true; 
}).mousemove(function(e) 
{ 
    if(mouseDown) { 
    var i = 0; 
    while (tab[i]) 
    { 
     tab[i].beginPath(); 
     tab[i].moveTo(lastEvent.offsetX, lastEvent.offsetY); 
     tab[i].lineTo(e.offsetX, e.offsetY); 
     tab[i].strokeStyle = color; 
     tab[i].stroke(); 
     i += 1; 
    } 
     lastEvent = e; 
    } 
}).mouseup(function(e) 
{ 
    mouseDown = false; 
}).mouseleave(function() 
{ 
    var i = 0; 
    while (tab[i]) 
    { 
    tab[i].mouseup() 
    i += 1; 
    } 
}); 
관련 문제