2011-04-04 89 views
0

我有一個腳本,它在畫布上繪製圖像並允許人們在該圖像上繪製線條。我想從腳本的其他地方獲取上下文(即具有各種jQuery函數的頭文件)。這可能嗎?從腳本的其他位置獲取畫布上下文

我的意思是這樣的:

頁眉:

saveInfo = function() 
{ 
    //save all the inputs 

    //get the context of the canvas so we can find some properties 
} 

clearInfo = function() 
{ 
    //clear the inputs 

    //get the context of the canvas so we can clear it and redraw the main image 
} 

包含的文件

<script type="text/javascript"> 
    //this is the script that produces the drawing functionality initially that I already have 
</script> 

編輯:我知道這似乎是顯而易見的,從而美化,每當有人繪製一條線在包含腳本的畫布中,我將其添加到名爲paths的json數組中。我需要能夠在保存部分得到這個。

+0

您的網頁上有多少幅畫布?他們有唯一的ID嗎?輸入是否與特定的畫布相關聯? – Phrogz 2011-04-04 15:05:32

回答

1
var context = document.getElementById("myCanvasId").getContext("2d"); 

...可以在腳本中的任何位置工作。

+0

如果只有一個畫布:'document.getElementsByTagName('canvas')[0] .getContext('2d');' – Phrogz 2011-04-04 15:06:12

0

爲什麼不創建全局函數來執行所需的語義操作,而不是直接進入畫布?例如:

saveInfo = function(){ 
// save all the inputs 
    var props = getContextProperties(); 
}; 

clearInfo = function(){ 
    // clear the inputs 
    redrawCanvas(); 
}; 

$(function(){ 
    var canvas = $('canvas')[0]; 
    var ctx = canvas.getContext('2d'); 
    getContextProperties = function(){ 
    return { w:canvas.width, h:canvas.height }; 
    }; 
    redrawCanvas = function(){ 
    ctx.save(); 
    ctx.setTransform(1,0,0,1,0,0); 
    ctx.clearRect(0,0,canvas.width,canvas.height); 
    ctx.restore(); 
    ctx.beginPath(); 
    // ... 
    }; 
});