2015-05-27 87 views
0

我是HTML5新手,請原諒我的無知。 我只是試圖在畫布上繪製圖像,代碼運行時沒有任何錯誤,但圖像未繪製。drawImage not drawing image

以下是HTML和JS。

var image 
 
var canvas; 
 
var context; \t 
 
var canvasWidth; 
 
var canvasHeight; 
 
window.onload = function(){ 
 
    canvas= document.getElementById("canvas"); 
 
    context=canvas.getContext("2d"); \t 
 
    canvasWidth = canvas.width; 
 
    canvasHeight = canvas.height; \t 
 
    image = document.createElement("img"); 
 
    image.onload = function(){ rotate(); } ; 
 
    image.src = "images/roller.png"; 
 
} 
 

 
function rotate() { 
 
    // Clear the canvas 
 
    context.clearRect(0, 0, canvasWidth, canvasHeight); 
 
\t 
 
    // Move registration point to the center of the canvas 
 
    context.translate(canvasWidth/2, canvasWidth/2); 
 
\t 
 
    // Rotate 1 degree 
 
    context.rotate(Math.PI/180); 
 
    
 
    // Move registration point back to the top left corner of canvas 
 
    context.translate(-canvasWidth/2, -canvasWidth/2); 
 
\t 
 
    context.drawImage(image,0,0); 
 
}
<div style="margin: 0 auto; height:400px; width:900px; overflow:hidden;"> 
 
<canvas id="canvas" style="margin:0 auto; width:900px; height:auto" align="center"></canvas> 
 
<div style="height:30px; width:50px; position:relative; margin-top:-30%"></div> 
 
</div>

感謝您的幫助提前:)

+0

我設法讓一些東西在jsfiddle中工作,但它幾乎立即崩潰。這就像一個spirograph,是嗎? – Andy

+0

我想繪製一個旋轉或旋轉的圖像,我將添加這個'setInterval(rotate,1000);'結束行'rotate()'函數 – Kami

+0

添加對image.onerror的支持以查看是否存在圖像加載錯誤(f.ex.錯誤的路徑,大寫,數據...)。 – K3N

回答

0

這裏有一些事情你應該嘗試:

你不應該設置在CSS畫布大小,它一切都會搞砸。相反申報畫布的大小,JS代碼中:

canvas.width = 900; 
canvas.height = 400; //note that you can't set the canvas height to auto. 
canvasWidth = canvas.width; 
canvasHeight = canvas.height; 

2移動圖像的中心,否則它會消失

3重拍你的旋轉功能,包括保存()和restore()你的畫布,如下所示:

function rotate() { 
    // Clear the canvas 
    context.clearRect(0, 0, canvasWidth, canvasHeight); 

    //Save the canvas 
    context.save(); 

    // Move registration point to the center of the canvas 
    context.translate(canvasWidth/2, canvasWidth/2); 

    // Rotate 1 degree 
    context.rotate(Math.PI/180); 

    //Draw the image so that it appears rotated. Rotation at the center of the image. 
    context.drawImage(image,canvasWidth/2-image.width/2, canvasWidth/2-image.height/2); 
    // Restore the canvas 
context.restore(); 
}