2014-08-27 9 views
0

이 예제에서 이미지가 캔버스에 표시되지 않는 이유는 무엇입니까?왜 이미지가 표시되지 않습니까?

코드 :

<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
<script> 
/* 
var lockOrientation = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; 
screen.lockOrientation('landscape'); 

if (lockOrientation("landscape-primary")) { 
    screen.lockOrientation('landscape'); 
} 
*/ 
var canvas = document.getElementById('myCanvas'); 
var context = canvas.getContext('2d'); 
var x = 10; 
var y = 10; 
var width = 470; 
var height = 310; 

var imageObj = new Image(); 

    imageObj.onload = function() { 
     context.drawImage(imageObj, x, y, width, height); 
    }; 
    imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; 
</script> 
</head> 
<body> 
    <canvas id="myCanvas" width="470" height="310" style="border:5px solid #123456;"></canvas> 
</body> 
</html> 
+1

는 종료 태그'' – Be0wulf

+1

브라우저의 콘솔 오류를 확인하기 전에 스크립트를 넣어보십시오. 이유를 알게 될 것입니다. http://jsfiddle.net/oxokcL3q/ – karthikr

답변

1

당신은 문서 페이지의 요소를 선택하기 전에로드 될 때까지 기다릴 필요가있다.

은 다음과 같이 코드를 포장하십시오 :

window.onload = function() { 
    // your code goes here 
}; 
+0

코드가 항상 onload에 있어야하거나 외부에 배치 될 수 있습니까? 나는 당신이 html 문서의 끝 부분에 그것을 놓는다면 먼저 읽거나 페이지가 마지막에로드한다는 것을 읽을 것이다. 이것은 일부 응용 프로그램을 개발할 때 큰 역할을합니다. 파이어 폭스 OS가 좋아하는 것을 알고 계십니까? –

관련 문제