2014-01-10 168 views
0

我想創建一個按鈕來清除畫布,但沒有成功。清除畫布按鈕

我給這家

JS

function clearcanvas1(){ 
ctx.clearRect(0, 0, canvas.width, canvas.height); 
var w = canvas.width; canvas.width = 1; canvas.width = w; 
} 

HTML代碼

<button onmouseover="clearcanvas1()">clear</button> 

我已經試過其他選項,如

canvas.width = canvas.width; 

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); 

目前,我已經用location.reload函數取代了清除按鈕,但它在我想獨立操作的同一頁面上打亂了輔助畫布。 我怎樣才能做到這一點?

回答

2

你似乎沒有被得到canvas元素在函數中(或者實際上它的上下文)...

function clearcanvas1() 
{ 
    var canvas = document.getElementById('canvas'), 
     ctx = canvas.getContext("2d"); 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
} 

顯然,您需要更新document.getElementById()代表正確的ID爲您標記,或者您可以使用document.getElementsByTagName()

+0

謝謝你,完美的作品。 我不知道你必須像上面那樣工作。乾杯! – user3178364

0

上的按鈕調用這個函數的

function clearall() 
{ 
    var canvas=document.getElementById("canvas+id"); 
    var context=canvas.getContext("2d"); 
    context.clearRect(0,0,canvas.width,canvas.height); 
} 

希望這會幫助你。請注意,此功能將清除畫布中的所有內容。