Why is canvas.arc not working?
Asked Answered
K

3

5

I have this code at the end of a web page:

var canvas = document.getElementByID("canvas");
var ctx = canvas.getContext("2d");
canvas.style.width = $(window).width();
canvas.style.height = $(window).height();
ctx.arc(50, 50, 50, 0, Math.PI * 2, false);
$(window).resize(function () { 
  canvas.style.width = $(window).width();
  canvas.style.height = $(window).height();
  console.log("resize");
});

But nothing shows up. I know that the problem is with the arc function because ctx.fillRect(0, 0, 100, 100); works fine.

Any idea what I am doing wrong?

(Yes, I do have JQuery)

Knell answered 11/6, 2011 at 22:38 Comment(0)
C
6

You need to use ctx.beginPath() before ctx.arc() and ctx.stroke() afterwards, this tells canvas to clean its buffer before it starts drawing, and to output buffer to the canvas after it finishes. fillRect()/strokeRect() already handles those begin/end tasks for you.

Cosmetic answered 11/6, 2011 at 22:41 Comment(0)
I
2

You need to do a path:

var canvas = document.getElementByID("canvas");
var ctx = canvas.getContext("2d");
canvas.style.width = $(window).width();
canvas.style.height = $(window).height();

ctx.beginPath(); // <-- start a path

ctx.arc(50, 50, 50, 0, Math.PI * 2, false); // <-- add the arc to the path

ctx.strokeStyle = "#000000"; // <-- set fill color
ctx.stroke(); // <-- draw the arc

$(window).resize(function () { 
  canvas.style.width = $(window).width();
  canvas.style.height = $(window).height();
  console.log("resize");
});
Iggie answered 11/6, 2011 at 22:42 Comment(0)
C
1
  1. First of all ID in first line needs to be Id.
  2. Then for the arc function there needs to be a ctx.beginPath(); function to start.
  3. after that give it a colour eg. ctx.fillStyle = "Colour You Want";
  4. then, your arc function ctx.arc(50, 50, 50, 0, Math.PI * 2, false); as it is
  5. and after that at the end put ctx.fill(); to complete the process.
Centillion answered 23/6, 2020 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.