2016-08-29 3 views
-1
<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 

    <canvas id="spriteCanvas" width="500" height="500"> 
     <img id="coin" width="440" height="40" src="coin.png"> 
    </canvas> 

</body> 
</html> 

이미지를 캔버스 요소 안에 넣으려고했지만 브라우저에 표시되지 않습니다. Canvas 요소 외부에 배치하면 이미지 태그가 표시되므로 이미지 태그가 작동하는 것을 알고 있습니다. 또한 캔버스 요소를 검사하면 이미지가 내부에 있음을 알 수 있지만 치수는 0입니다. 왜 이것이 작동하지 않는지 설명 할 수 있습니까?캔버스 내부에 이미지가 표시되지 않음

편집 : 내 원본 코드는 자바 스크립트를 통해 이미지를 추가했지만 캔버스에 표시되지 않습니다. 위와 똑같은 문제를 일으켰습니다. 하지만 방금 "onload"가 누락되었다는 것을 깨달았습니다.

원래 코드 :

var coinImage = new Image(); 
coinImage.src = "coin.png"; 
var sCanvas = document.getElementById('spriteCanvas'); 

function Sprite(canvas, width, height, image){ 
    this.context = canvas.getContext("2d"); 
    this.width = width; 
    this.height = height; 
    this.image = image; 
} 

Sprite.prototype.render = function() { 
    var that = this; 
    this.context.drawImage(that.image, 0, 0); 
} 

function init() { 
    var coin = new Sprite(sCanvas, 100, 100, coinImage); 
    coin.render(); 
} 

init(); 

편집 해 코드하십시오 <canvas> 태그가 어떻게 작동하는지

var coinImage = new Image(); 
coinImage.src = "coin.png"; 
var sCanvas = document.getElementById('spriteCanvas'); 

function Sprite(canvas, width, height, image){ 
    this.context = canvas.getContext("2d"); 
    this.width = width; 
    this.height = height; 
    this.image = image; 
} 

Sprite.prototype.render = function() { 
    var that = this; 
    this.context.drawImage(that.image, 0, 0); 
} 

coinImage.onload = function() { 
    var coin = new Sprite(sCanvas, 100, 100, coinImage); 
    coin.render(); 
} 
+0

''태그를 사용하는 방법을 찾아보십시오. 이것이 작동하는 방식은 아닙니다. 캔버스에 그려 넣고 HTML 요소를 안에 넣지 마십시오. –

답변

1

이 없습니다. 이미지를 캔버스에 표시하려면 JavaScript를 사용하여 이미지의 픽셀을 캔바스에 배치해야합니다.

<canvas>은 캔버스입니다. 그것들은 프로그래밍 방식으로 그릴 수있는 요소입니다. 페이지에 이미지를 표시하려는 경우 캔버스가 필요하지 않으므로 <img> 태그 만 있으면됩니다. 실제로 요소는 <canvas>에 배치하면 안됩니다.

CanvasRenderingContext2D.drawImage() 및이 자습서 HTML5 Canvas Image Tutorial을 살펴보십시오.

그리고이 조각 : 당신이 그릴하고자하는 이미지가 아닌 경우

drawImage(image,x,y) 

: 사용, 캔버스에 다음과 같은 방법을 이미지를 그릴

var canvas = document.getElementById("painting"), 
 
    ctx = canvas.getContext("2d"), 
 
    image = new Image(); 
 

 
image.onload = function() { 
 
    ctx.drawImage(image, 30, 50); 
 
}; 
 

 
image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>

1

DOM에서는 이미 몇 줄의 자바 스크립트가있는 URL에서 직접 이미지를로드 할 수 있습니다.

function loadAndDrawImage(url) 
{ 
    // Create an image object. This is not attached to the DOM and is not part of the page. 
    var image = new Image(); 

    // When the image has loaded, draw it to the canvas 
    image.onload = function() 
    { 
     // draw image... 
    } 

    // Now set the source of the image that we want to load 
    image.src = url; 
} 
loadAndDrawImage("http://www---.png"); 
관련 문제