2014-09-27 89 views
1

我有,我有如何將畫布的大小設置爲其背景圖片?

canvas{ 
    border: solid black 2px; 
    background:url("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png"); 
    background-repeat:no-repeat; 
    } 

畫布對象下面的CSS代碼如何使畫布等於背景圖像的尺寸大小?

+1

獲取背景圖像的大小,畫布大小設置爲它,有沒有爲這一個步驟。 – Shomz 2014-09-27 11:52:20

回答

5

如果這是一個不變的圖像,請使用CSS中的width和height屬性。

canvas{ 
    border: solid black 2px; 
    background: url("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png"); 
    background-repeat:no-repeat; 
    width: 200px; 
    height: 298px; 
} 

如果這是一個動態的圖像,使用JavaScript。

HTML:

JS:

function resizeCanvas() 
{ 
    var img = document.getElementById('dynamic_img'); 
    var width = img.clientWidth; 
    var height = img.clientHeight; 

    var canvas = document.getElementById('canvas'); 
    canvas.style.width = width; 
    canvas.style.height = height; 
}