2014-07-16 6 views
2

HTML5의 canvas 태그와 JavaScript를 사용하여 페이지에서 여러 이미지를 자르고 싶습니다. 문제는 페이지에 이미지 중 하나만 표시된다는 것입니다.한 번에 여러 캔버스 사용

어떻게해야합니까? 내가 노력 코드는 다음과 같습니다 :

<canvas id="myCanvas" width="300" height="300"></canvas> 
<canvas id="myCanvas" width="300" height="300"></canvas> 
<canvas id="myCanvas" width="300" height="300"></canvas> 
<script> 
    var canvas = document.getElementById('myCanvas'); 
    var context = canvas.getContext('2d'); 
    var imageObj = new Image(); 

    imageObj.onload = function() { 
    // draw cropped image 
    var sourceX = 0; 
    var sourceY = 0; 
    var sourceWidth = 200; 
    var sourceHeight = 150; 
    var destWidth = sourceWidth; 
    var destHeight = sourceHeight; 
    var destX = canvas.width/2 - destWidth/2; 
    var destY = canvas.height/2 - destHeight/2; 

    context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight); 
    }; 

imageObj.src ='http://static.adzerk.net/Advertisers/3478c54721cd466fb6f7d3afe16e97d4.gif'; 

</script> 

바이올린 : http://jsfiddle.net/soheilyou/54VTh/, 각 캔버스 같은 id를 사용하고 말한대로 Some Guy

+2

'ID'의 포인트입니다. 더 자세히 살펴보고 싶을 수도 있습니다. 따라서 HTML을 배우는 것이 좋습니다. 그 외에도 모든 캔버스의 컨텍스트를 가져와 모든 캔버스를 그릴 필요가 있습니다. –

+0

고유 한 ID로 모든 캔버스를 개별적으로 처리해야하며, 그렇지 않으면 클래스를 사용하고 점진적으로 조치를 수행해야합니다. – Sam

답변

0

- 그건 더 노 없습니다. 각자 고유 한 id을 주거나 클래스를 대신 사용해보십시오.

그런 다음 요소 하나 하나를 잡아내는 것입니다. do with JavaScript 또는 jQuery (아래)를 사용하면 더 쉽게 할 수 있습니다.

체크 아웃 this updated Fiddle 또는이 자바 스크립트 코드 조각 참조 : 그것은 * 한 * 요소에 고유하는

var canvases = $('.myCanvas'); 
$(canvases).each(function() { 
    var canvas = $(this).get(0); //Grab the canvas node from the jQuery container. 
    var context = canvas.getContext('2d'); 
    var imageObj = new Image(); 

    imageObj.onload = function() { 
     var sourceX = 0; 
     var sourceY = 0; 
     var sourceWidth = 200; 
     var sourceHeight = 150; 
     var destWidth = sourceWidth; 
     var destHeight = sourceHeight; 
     var destX = canvas.width/2 - destWidth/2; 
     var destY = canvas.height/2 - destHeight/2; 

     context.drawImage(imageObj, sourceX, sourceY, 
          sourceWidth, sourceHeight, destX, 
          destY, destWidth, destHeight); 
    }; 

    imageObj.src = 'path/to/your/image.png'; 
});