2011-04-04 54 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(); 
    // ... 
    }; 
});