2014-02-22 5 views
1

인터넷에서이 코드를 발견했으며 그 코드를 가지고 놀았습니다. 그것은 캔버스의 어떤 지점에 텍스트를 추가합니다. 그러나 캔버스에 새 텍스트를 추가하면 이전 텍스트가 삭제됩니다. 캔버스에 여러 텍스트 인스턴스가 동시에 존재할 수있는 쉬운 방법이 있습니까?HTML5 캔버스에 여러 개의 텍스트 인스턴스 추가

저는 JS에 익숙하고 새로운 텍스트가 저장되면 텍스트를 삭제하는 코드를 볼 수 없습니다. x와 y 좌표와 함께 배열의 모든 텍스트를 저장할 필요가 없기를 바랄뿐입니다.

코드는 아래에 있지만 일부 외부 JS없이 작동하지 않으므로 여기에서 복사 한 작업 버전에 대한 링크가 있습니다. 어떤 제안

<!DOCTYPE html> 
<html> 
<head> 
    <link rel="stylesheet" type="text/css" href="css/css.css"> 
</head> 
<body> 
    <div id="main"> 
     <canvas id="c"></canvas><!-- the canvas --> 
    </div> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
    <script type="text/javascript" src="text.js"></script><!-- Library to help text --> 
    <script type="text/javascript"> 
$('#c').mousedown(function(e){ 
      if ($('#textAreaPopUp').length == 0) { 
       var mouseX = e.pageX - this.offsetLeft + $("#c").position().left; 
       var mouseY = e.pageY - this.offsetTop; 

       //append a text area box to the canvas where the user clicked to enter in a comment 
       var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+mouseY+"px;left:"+mouseX+"px;z-index:30;'><textarea id='textareaTest' style='width:100px;height:50px;'></textarea>"; 
       var saveButton = "<input type='button' value='save' id='saveText' onclick='saveTextFromArea("+mouseY+","+mouseX+");'></div>"; 
       var appendString = textArea + saveButton; 
       $("#main").append(appendString); 
      } else { 
       $('textarea#textareaTest').remove(); 
       $('#saveText').remove(); 
       //$('#textAreaPopUp').remove(); 
       var mouseX = e.pageX - this.offsetLeft + $("#c").position().left; 
       var mouseY = e.pageY - this.offsetTop; 
       //append a text area box to the canvas where the user clicked to enter in a comment 
       var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+mouseY+"px;left:"+mouseX+"px;z-index:30;'><textarea id='textareaTest' style='width:100px;height:50px;'></textarea>"; 
       var saveButton = "<input type='button' value='save' id='saveText' onclick='saveTextFromArea("+mouseY+","+mouseX+");'></div>"; 
       var appendString = textArea + saveButton; 
       $("#main").append(appendString); 
      } 
     }); 

     function saveTextFromArea(y,x){ 
      //get the value of the textarea then destroy it and the save button 
      var text = $('textarea#textareaTest').val(); 
      $('textarea#textareaTest').remove(); 
      $('#saveText').remove(); 
      $('#textAreaPopUp').remove(); 
      //get the canvas and add the text functions 
      var canvas = document.getElementById('c'); 
      var ctx = canvas.getContext('2d'); 
      var cw = canvas.clientWidth; 
      var ch = canvas.clientHeight; 
      canvas.width = cw; 
      canvas.height = ch; 
      //break the text into arrays based on a text width of 100px 
      var phraseArray = getLines(ctx,text,100); 
      // this adds the text functions to the ctx 
      CanvasTextFunctions.enable(ctx); 
      var counter = 0; 
      //set the font styles 
      var font = "sans"; 
      var fontsize = 12; 
      ctx.strokeStyle = "rgba(0,0,0,1)"; 
      ctx.shadowOffsetX = 0; 
      ctx.shadowOffsetY = 0; 
      ctx.shadowBlur = 0; 
      ctx.shadowColor = "rgba(0,0,0,1)"; 
      //draw each phrase to the screen, making the top position 20px more each time so it appears there are line breaks 
      $.each(phraseArray, function() { 
       //set the placement in the canvas 
       var lineheight = fontsize * 1.5; 
       var newline = ++counter; 
       newline = newline * lineheight; 
       var topPlacement = y - $("#c").position().top + newline; 
       var leftPlacement = x - $("#c").position().left; 
       text = this; 
       //draw the text 
       ctx.drawText(font, fontsize, leftPlacement, topPlacement, text); 
       ctx.save(); 
       ctx.restore(); 
      }); 
      //reset the drop shadow so any other drawing don't have them 
      ctx.shadowOffsetX = 0; 
      ctx.shadowOffsetY = 0; 
      ctx.shadowBlur = 0; 
      ctx.shadowColor = "rgba(0,0,0,0)"; 
     } 

     function getLines(ctx,phrase,maxPxLength) { 
      //break the text area text into lines based on "box" width 
      var wa=phrase.split(" "), 
      phraseArray=[], 
      lastPhrase="", 
      l=maxPxLength, 
      measure=0; 
      ctx.font = "16px sans-serif"; 
      for (var i=0;i<wa.length;i++) { 
       var w=wa[i]; 
       measure=ctx.measureText(lastPhrase+w).width; 
       if (measure<l) { 
        lastPhrase+=(" "+w); 
       }else { 
        phraseArray.push(lastPhrase); 
        lastPhrase=w; 
       } 
       if (i===wa.length-1) { 
        phraseArray.push(lastPhrase); 
        break; 
       } 
      } 
      return phraseArray; 
     } 
    </script> 
    <script src="js/text.js"></script> 
    <script src="js/js.js"></script> 
</body> 

답변

2

이유에 미리 http://oldstatic.travisberry.com/demos/canvas-text-demo/index.html

덕분에 캔버스 크기는 때마다 설정된다. 그런 일이 발생하는 경우 :

을 사용자 에이전트가 비트 맵 크기를 설정하는 는 다음 단계를 실행해야합니다, 폭과 높이 인 경우 :
3. 새에 스크래치 비트 맵의 ​​크기를 조정 ...

을 너비와 높이가 이면 완전히 투명 한 검정색으로 바뀝니다.

<div id="main"> 
    <canvas id="c" width=500 height=300></canvas> <!-- any size you want --> 
</div> 
:

Source

그렇게 할 우선 (아래와 같이) 두 요소 태그 캔버스 요소의 크기를 미리 또는 코드의 상위 범위이다

그런 다음 JavaScript에서 다음 줄을 제거하십시오.

function saveTextFromArea(y,x){ 
     ...snipped for example... 
     var canvas = document.getElementById('c'); 
     var ctx = canvas.getContext('2d'); 
     var cw = canvas.clientWidth; 
     var ch = canvas.clientHeight; 
     //canvas.width = cw;    // remove this line 
     //canvas.height = ch;   // remove this line 

     ...snipped for example... 
+0

감사합니다. – Sam

관련 문제