HMdeveloper
HMdeveloper

Reputation: 2884

Can not draw a circle on top of rectangle in html5

I am using html5 and I want to draw a circle on top of a rectangle so I used the following html code:

<canvas id="myCanvas" style="z-index: 1;width:70%;height: 70%;float: left;">

<canvas id="c1" style="z-index: 2;width:10%;height: 10%;float: left;"></canvas>

and following js code:

  $(document).ready(function() {
  var c=document.getElementById("myCanvas");
  var ctx=c.getContext("2d");
  ctx.rect(10,10,$("#myCanvas").height(),$("#myCanvas").width());
  ctx.fillStyle = 'yellow';
  ctx.fill();
  ctx.stroke();


  var canvas = document.getElementById('c1');
  var context = canvas.getContext('2d');
  var centerX = $("#myCanvas").height()/ 2;
  var centerY = $("#myCanvas").width() / 2;
  var radius = 70;

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  context.fillStyle = 'green';
  context.fill();
  context.lineWidth = 5;
  context.strokeStyle = '#003300';
  context.stroke();

  });

and here is the jfiddle link:

jfiddle

Now the problem is that the circle is not shown and I do not know what is the problem!!! Can anyone help me?

Upvotes: 0

Views: 778

Answers (2)

4m1r
4m1r

Reputation: 12552

Are you sure you need two canvases? I would do it on one.

$(document).ready(function() {

    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.rect(10,10,$("#myCanvas").height(),$("#myCanvas").width());
    ctx.fillStyle = 'yellow';
    ctx.fill();
    ctx.stroke();

    var centerX = $("#myCanvas").height()/ 2;
    var centerY = $("#myCanvas").width() / 2;
    var radius = 70;

    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'green';
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = '#003300';
    ctx.stroke();

});

http://jsfiddle.net/7FuL9/2/

Upvotes: 1

Sid
Sid

Reputation: 1144

Why do you need two canvas tags to do this? This can be done with just one canvas. Here is a JSBin that draws a circle on top of a rectangle.

Upvotes: 1

Related Questions