-1

I am new to javascript and canvas programming. I have a function drawLines(canvasIndex,startPosition) which is responsible for drawing lines on a canvas. It takes in two arguments canvasIndex which represents the canvas which I am drawing on and startPosition represents the starting point of the line. Now I am calling the function in my code. The below shows the way in which I am calling the function.

<script type="text/javascript">
function drawLines(canvasIndex,startPosition)
{
...
}
drawLines(0,0);
drawLines(1,0);
</script>

Now during the execution, the lines are drawn only on the last canvasIndex specified. Meaning, if I call it in this sequence,

drawLines(0,0);
drawLines(2,0);

it draws the lines only on the second canvas and not sequentially. I want it to be such that it draws sequentially by just this sort of function calls. Please help me with this problem.

1 Answer 1

0

A Demo: http://jsfiddle.net/m1erickson/drFV4/

First, create an array to hold your canvas contexts:

var contexts=[];

Then get references to your canvas elements and create contexts for them.

Put the contexts in the contexts array:

HTML:

<canvas id="canvas0" width=100 height=100></canvas>
<canvas id="canvas1" width=100 height=100></canvas>
<canvas id="canvas2" width=100 height=100></canvas>

JavaScript:

var canvas0=document.getElementById("canvas0");
contexts.push(canvas0.getContext("2d"));
var canvas1=document.getElementById("canvas1");
contexts.push(canvas1.getContext("2d"));
var canvas2=document.getElementById("canvas2");
contexts.push(canvas2.getContext("2d"));

Create your drawLines function:

function drawLines(canvasIndex,startPosition){
    var ctx=contexts[canvasIndex];
    ctx.beginPath();
    ctx.moveTo(startPosition,10);
    ctx.lineTo(50,50);
    ctx.lineWidth=5;
    ctx.stroke();
}

Finally, call your function as desired:

drawLines(0,0);
drawLines(1,50);
drawLines(2,100);
2
  • Thank you very much!!! One quick question, was the problem because of "Closure in a loop" in javascript? Or was it that it could not get the references?
    – Nikhil
    Mar 20, 2014 at 17:30
  • You're welcome! Difficult to say why the last canvas was getting all the drawings without seeing more of your code. I suspect since the drawing was being done--but on the wrong canvas, that scoping (closures) was not your issue.
    – markE
    Mar 20, 2014 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.