HTML5 Canvas with jCanvas: How to remove a layer

2.5k views Asked by At

I am using jCanvas to build a HTML5 app, I need to remove a layer, which is a black circle on the canvas, you can see the code here.

var cvLingualWidth = 945;
var cvLingualHeight = 100;

var cvLingual = document.getElementById("cvLingual");

function drawGrid() {
    var contextLingual = cvLingual.getContext("2d");

    for (var y = 0.5; y < cvLingualHeight; y += 6) {
        contextLingual.moveTo(0, y);
        contextLingual.lineTo(cvLingualWidth, y);
    }

    contextLingual.strokeStyle = "#DDD";
    contextLingual.stroke();
}

function drawCircle() {
    $("#cvLingual").drawArc({
        layer: true,
        name: "circleLayer_18",
        strokeStyle: "#000",
        strokeWidth: 2,
        x: 42,
        y: 70,
        radius: 8
    });
}

function clearCircle() {
    var circleLayer = $("#cvLingual").getLayer("circleLayer_18");
    // TODO
}

$(function () {
    drawGrid();
    drawCircle();
    $("#clear").click(function(){
        clearCircle();
    });
})

I tried removeLayer() but its not working. If I clear the canvas, the entire UI will be gone.

How can I clear the circle without affecting the background gridlines?

1

There are 1 answers

0
caleb531 On BEST ANSWER

According to the removeLayer() documentation, the removeLayer() method does not update the canvas automatically. You will need to do this afterwards using the drawLayers() method.

$("#cvLingual").removeLayer("myLayer").drawLayers();

However, the drawLayers() method works by clearing the canvas and redrawing all jCanvas layers, which means that your gridlines will disappear. To fix this, use jCanvas's drawLine() method to draw your gridlines, like so:

$canvas.drawLine({
    layer: true,
    strokeStyle: "#DDD",
    strokeWidth: 1,
    x1: 0, y1: y,
    x2: cvLingualWidth, y2: y
});

As a side note, if you are planning on drawing the circle again later (after removing it), I recommend setting the layer's visible property to false temporarily. Then, when you are ready to show the circle again, set its visible property to true. Note that you will need to call drawLayers() to update the canvas in both instances.

Hide the circle:

$("#cvLingual").setLayer({
    visible: false
}).drawLayers();

Show the circle again:

$("#cvLingual").setLayer({
    visible: true
}).drawLayers();

Finally, for your convenience, I have forked your fiddle and have implemented the above suggestions.