2013-07-04 4 views
1

HTML 5 캔버스 안에 이미지 주위에 텍스트를 줄 바꿈이 가능합니까? 예를 들어 일부 자바 스크립트 프레임 워크를 사용하고 있습니까? KineticJS를 살펴 보았지만 유용한 것을 찾을 수 없었습니다.캔버스에 이미지 주위에 텍스트 줄 바꾸기

편집 :

내 질문에 불분명 한 것 같습니다. 나는이 아이크 뭔가를 찾고 있어요 : 당신은 캔버스 변환을 사용하여 이미지 (사각형)의 주위에 텍스트를 래핑 할 수

http://www.monkeydoit.com/images/panda2.gif

답변

3

(+ 번역 회전)

enter image description here 예를 들어

, 캔버스를 회전하고 이미지의 오른쪽 아래로 텍스트를 그리는 방법은 다음과 같습니다.

// save the untransformed state of the context 
ctx.save(); 

// translate to the top-right corner of the image 
// (x/y properties have been added to the standard img element) 
ctx.translate(image.x+image.width,image.y); 

// rotate the canvas 90 degrees (PI/2 radians) 
ctx.rotate(Math.PI/2); 

// the canvas is now properly moved and rotated 
// so we can just draw the text at [0,0] 
ctx.fillText(subtext,0,0); 

// restore the context to its untransformed state 
ctx.restore(); 

이 많은 단어 context.measureText를 사용하여 측면에 맞는 방법을 계산합니다

var end=0; 

var subtext=""; 

while(ctx.measureText(text.split(" ",end+1).join(" ")).width<=length) 
{ 
    subtext=text.split(" ",end+1).join(" "); 
    end++; 
} 

흥미로운 향상은 모서리가 둥근 사각형의 주위에 텍스트를 그릴하는 것입니다. 여기

는 코드와 바이올린입니다 : http://jsfiddle.net/m1erickson/U2hE3/

<!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; padding:10px; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 

    var rect={x:40,y:40,width:150,height:120}; 

    var text="This is some text that wraps on the outside of a rectangle."; 

    var font="14px Verdana"; 

    drawTextAroundRect(rect,text,7,font); 


    function drawTextAtAngle(text,length,x,y,radians){ 

     // if text is empty then return 
     if(text.length==0){return;} 

     var end=0; 
     var subtext=""; 

     if(ctx.measureText(text).width<=length){ 

      // all the text fits 
      subtext=text; 

     }else{ 

      // calc how many words will fit on this length 
      while(ctx.measureText(text.split(" ",end+1).join(" ")).width<=length) 
      { 
       subtext=text.split(" ",end+1).join(" "); 
       end++; 
      } 

     } 

     // draw the text at the appropriate angle 
     ctx.save(); 
     ctx.translate(x,y); 
     ctx.rotate(radians); 
     ctx.fillText(subtext,0,0); 
     ctx.restore(); 

     // return any text that didn't fit for further processing 
     if(end==text.length){ 
      return(""); 
     }else{ 
      return(text.substr(subtext.length)); 
     } 

    } 


    function drawTextAroundRect(rect,text,textPadding,font){ 

     // set the font 
     ctx.font=font; 

     // top 
     text=drawTextAtAngle(text,rect.width,rect.x,rect.y-textPadding,0); 

     // right 
     text=drawTextAtAngle(text,rect.height,rect.x+rect.width+textPadding,rect.y,Math.PI/2); 

     // bottom 
     text=drawTextAtAngle(text,rect.width,rect.x+rect.width,rect.y+rect.height+textPadding,Math.PI); 

     // left 
     text=drawTextAtAngle(text,rect.height,rect.x-textPadding,rect.y+rect.height,Math.PI*1.5); 

     // draw the rect (just for illustration) 
     ctx.beginPath(); 
     ctx.rect(rect.x,rect.y,rect.width,rect.height); 
     ctx.stroke(); 

    } 


}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=300 height=250></canvas> 
</body> 
</html> 

[더 추가 바꿈 코드 주어진 질문자의 설명]

당신은 텍스트와 사용의 폭을 얻을 수 context.measureText을 사용할 수 있습니다 이미지 주위에 텍스트를 감싸는 것.

enter image description here

지정된 텍스트 폭 당신은 텍스트를 원하는 너비를 초과 다음 행으로 진행하여 줄 바꿈을 구축 할 수 있습니다.

그림을 감싸는 경우 원하는 너비가 2 개가됩니다. 텍스트가 이미지로 들어가는 동안 짧아지면 길어집니다. http://jsfiddle.net/m1erickson/XM5Yp/

<!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(){ 

    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 

    var maxWidth = 350; 
    var lineHeight = 25; 
    var x = (canvas.width - maxWidth)/2; 
    var y = 60; 
    var text = "'Twas the night before Christmas, when all through the house. Not a creature was stirring, not even a mouse. The stockings were hung by the chimney with care in hopes that St. Nicholas soon would be there."; 

    ctx.font = '16pt Calibri'; 
    ctx.fillStyle = '#333'; 

    var imgWidth; 
    var imgHeight; 

    var img=new Image(); 
    img.onload=function(){ 

     imgWidth=img.width; 
     imgHeight=img.height; 

     ctx.drawImage(img,canvas.width-img.width,0) 

     wrapText(text, x, y, maxWidth, lineHeight); 

    } 
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg"; 


    function wrapText(text, x, y, maxWidth, lineHeight) { 

     var words = text.split(' '); 
     var line = ''; 

     var maxLineWidth=y>imgHeight+10?maxWidth:maxWidth-imgWidth; 

     for(var n = 0; n < words.length; n++) { 
     var testLine = line + words[n] + ' '; 
     var metrics = ctx.measureText(testLine); 
     var testWidth = metrics.width; 
     if(testWidth > maxLineWidth) { 
      ctx.fillText(line, x, y); 
      line = words[n] + ' '; 
      y += lineHeight; 
      maxLineWidth= y>imgHeight+10?maxWidth:maxWidth-imgWidth; 

     } 
     else { 
      line = testLine; 
     } 
     } 
     ctx.fillText(line, x, y); 
    } 

}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=400 height=325></canvas> 
</body> 
</html> 
+0

나는 이런 식으로 뭔가를 찾고 있어요 : http://www.monkeydoit.com/images/panda2.gif –

+0

아야 ... 오해 코드와 바이올린 여기

입니다! : p -하지만 설명 해줘서 고마워. 귀하의 필요에 맞는 원래 답변에 다른 솔루션을 추가했습니다. BTW, 그냥 div 요소를 사용하지 않고, 단락을 추가하고 팬더 이미지를 오른쪽으로 띄우면 어떨까요? – markE

관련 문제