I have a script that draws an image on a canvas and allows people to draw lines on this image. I want to get the context from elsewhere in the script (i.e. a header that has various jQuery functions). Is this possible?
What I mean is something like:
Header:
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
}
Included File
<script type="text/javascript">
//this is the script开发者_StackOverflow社区 that produces the drawing functionality initially that I already have
</script>
Edit: I realise this may seem obvious so to embellish, whenever someone draws a line on the canvas in the included script I add to a json array called paths. I need to be able to get this in the save section.
var context = document.getElementById("myCanvasId").getContext("2d");
... will work in any place in your script.
Instead of reaching into the canvas directly, why not create global functions to perform the semantic actions you want? For example:
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();
// ...
};
});
精彩评论