2016-07-09 10 views
1

I 이미지에 텍스트 쓰기에 대한 문제가 있습니다. 이미지를 반복해야합니다. 하지만 문제가 생겼어. 내가 할 때 마지막 이미지가 표시되고 이미지 크기가 작습니다. 아무도 날 도와주지?JavaScript 이미지에 텍스트 쓰기

var div=document.getElementById("locations"); 
 
var canvas; 
 

 
window.onload = function(){ 
 
    for(var i=0;i<10;i++){ 
 
     canvas=document.createElement("canvas"); 
 
     canvas.style.width="75px"; 
 
     canvas.style.height="75px" 
 

 
     var context = canvas.getContext("2d"); 
 
     var imageObj = new Image(); 
 
     imageObj.onload = function(){ 
 
      context.drawImage(imageObj, 0, 0); 
 
      context.font = "17px Calibri"; 
 
      context.fillText(i, 30, 36); 
 
     }; 
 
     imageObj.src = "image.png"; 
 
     div.appendChild(canvas); 
 
    }; 
 
}
<div id="locations"></div> 
 
<canvas id="myCanvas" width="75" height="75"></canvas>

결과 이미지가

Result Image

+0

imageObj.onload = 함수() { \t \t \t context.drawImage (imageObj, 0, 0); \t \t \t context.font = "17px Calibri"; \t \t \t context.fillText (i, 30, 36); \t \t \t canvas.style.width = imageObj.width + "px"; \t \t \t canvas.style.height = imageObj.height + "px" \t \t}; –

+0

작동하지 않습니다. 다시 문제가 생겼어. –

답변

0

사용 canvas.height 대신 CSS 스타일의 폭 값. 캔버스가 그려진 후에 CSS 스타일 값이 적용됩니다.

var div=document.getElementById("locations"); 
 
var canvas; 
 

 
window.onload = function(){ 
 
    for(var i=0;i<10;i++){ 
 
     canvas=document.createElement("canvas"); 
 
     canvas.width=75; 
 
     canvas.height=75; 
 

 
     var context = canvas.getContext("2d"); 
 
     var imageObj = new Image(); 
 
     imageObj.onload = function(){ 
 
      context.drawImage(imageObj, 0, 0); 
 
      context.font = "17px Calibri"; 
 
      context.fillText(i, 30, 36); 
 
     }; 
 
     imageObj.src = "http://placehold.it/350x150"; 
 
     div.appendChild(canvas); 
 
    }; 
 
}
<div id="locations"></div>