"getContext()" is working only in OnPaint event handler

707 Views Asked by At

I want to draw a line at a fix position in a Canvas. I've written the following code:

function drawVLine(){
    var ctx1 = myCanvas.getContext("2d");

    ctx1.reset();
    ctx1.lineJoin = "round";

    ctx1.save()
    ctx1.lineWidth = 2
    ctx1.strokeStyle = "green"
    var x = 50
    ctx1.beginPath()
    ctx1.moveTo(x, 0)
    ctx1.lineTo(x, myCanvas.height)
    ctx1.stroke()
    ctx1.restore()
}

This code works properly when I call it from event handler onPaint but if I call this function through some other function, it does nothing. I want to execute this function on certain signal and I don't want to call myCanvas.requestPaint() to trigger onPaint event and then draw the line.

Is it the case that Context can be fetched only from onPaint event?

EDIT:

according to comments and various attempts, I came to conclusion that, Painting methods can not be used out of onPaint events.

0

There are 0 best solutions below