我有一个脚本可以在画布上绘制图像,并允许人们在此图像上绘制线条。我想从脚本中的其他地方获取上下文(即具有各种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 :(得分:1)
var context = document.getElementById("myCanvasId").getContext("2d");
...将在您的脚本中的任何位置工作。
答案 1 :(得分: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();
// ...
};
});