سؤال

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)

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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");
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top