1

Is it possible to use the arc() and rect() functions to draw shapes inside of a div using javascript? Could you please give a simple example of a circle (drawn with 'arc()') inside of a div?

Edit: I fully understand the rect and arc function but I am getting a little bit tripped up by javascripts context.

I have created a div called appLights and have positioned it to the proper location. Now I am trying to draw just a simple circle in the top center of the div and am having trouble.

appLights = document.createElement("div");
appLights.style.position = "relative";
appLights.style.width = "30px";
appLights.style.height = "180px";
appLights.style.left = "105px";
appLights.style.top = "-175px";

var ctx = appLights.getContext('2d');
ctx.beginPath();
ctx.fillStyle = "rgb(123,123,123)";
ctx.arc(15,15,10,0, Math.PI * 2,true);
ctx.fill();
Karaja
  • 395
  • 6
  • 16
  • 2
    Yes you can... google javascript drawing with canvas – Patrick Evans Jul 24 '13 at 19:16
  • 1
    You gotta at least put a smaaaaaaaaall amount of effort in :) – null Jul 24 '13 at 19:17
  • I wouldn't be posting on here if I could get it to work. – Karaja Jul 24 '13 at 19:19
  • @Carter Then show your code so people can see why it won't work. That's what this site is for, not to give arbitrary examples. If you had showed your code, no matter how bad, you probably wouldn't have been downvoted at all. – mawburn Jul 24 '13 at 19:25
  • Yes, you can for example: Yes, something like below will create a circle inside div. var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.arc(100,75,50,0,2*Math.PI); ctx.stroke(); will draw a circle inside canvas – defau1t Jul 24 '13 at 19:33

1 Answers1

2

appLights MUST be a <canvas> element. You can't draw on a <div>

The first line in your code should be the following:

appLights = document.createElement("canvas");

Another issue is that you're not putting this new element anywhere on the page, so any drawing wouldn't show up until you appended it somewhere in the <body>

Jnatalzia
  • 1,687
  • 8
  • 14
  • The canvas made the circle appear but it was horizontally squished. Instead of being a circle with a a 10px radius it is a vertical 20px line. Also I do have the canvas appended. – Karaja Jul 24 '13 at 20:43
  • 1
    That's because of the way you're styling the canvas element. Canvas has it's own methods for changing width and height. Doing it through the CSS with skew your drawings to the canvas. [See here](http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5) – Jnatalzia Jul 24 '13 at 20:45
  • Thank you this all fixed it – Karaja Jul 24 '13 at 21:04