Wai Yan Hein
Wai Yan Hein

Reputation: 14791

Drawing multiple oval shapes on HTML canvas using JavaScript having an extra line

I am trying to know more about HTML canvas and JavaScript. Now I am trying to draw multiple oval shapes overlapping on each other and size will become smaller and smaller one after one. I can draw the shapes successfully.

This is my code

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;">
</canvas>
<script type="text/javascript">
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var center_x = 200;
    var center_y = 100;
    var width = 100;
    var height = 200;
    drawOvalShape(context, 200, 100, 100, 200);
    drawOvalShape(context, 200, 100, 80, 180);
    drawOvalShape(context, 200, 100, 60, 160);
    drawOvalShape(context, 200, 100, 40, 140);
    drawOvalShape(context, 200, 100, 20, 120);

    function drawOvalShape(context, center_x, center_y, width, height){
        context.ellipse(center_x, center_y, width, height,  90 * Math.PI/180, 0, 2 * Math.PI);

        context.stroke();
    }
</script>

When I run my code on the browser, it displays like this.

enter image description here

But the problem is why an extra line is included as below?

enter image description here

How can I get rid of that line?

Upvotes: 3

Views: 955

Answers (1)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

You are missing the context.beginPath. Please see this JSFIddle: https://jsfiddle.net/zwcd7hcw/

function drawOvalShape(context, center_x, center_y, width, height){
        context.beginPath()
        context.ellipse(center_x, center_y, width, height,  90 * Math.PI/180, 0, 2 * Math.PI);
        context.stroke();
}

 var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var center_x = 200;
    var center_y = 100;
    var width = 100;
    var height = 200;
    drawOvalShape(context, 200, 100, 100, 200);
    drawOvalShape(context, 200, 100, 80, 180);
    drawOvalShape(context, 200, 100, 60, 160);
    drawOvalShape(context, 200, 100, 40, 140);
    drawOvalShape(context, 200, 100, 20, 120);

    function drawOvalShape(context, center_x, center_y, width, height){
			context.beginPath()
        context.ellipse(center_x, center_y, width, height,  90 * Math.PI/180, 0, 2 * Math.PI);

       context.stroke();
    }
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;">
</canvas>

Upvotes: 5

Related Questions