What steps are involved in creating a circular shape on canvas?

I am trying to create a circular shape in the canvas using the code below. The code involves moving an object with keyboard keys, and I need help making the canvas shape into a circle without affecting the functionality of the code. I attempted to modify the code to create a circle, but the shape disappeared. Can someone provide guidance on how to achieve this?

I apologize for the additional text, I am required to add more content for some reason (make the canvas circle)(make the canvas circle)(make the canvas circle)

<!DOCTYPE html>
<html>
<head></head>
<body>
  <canvas id="myCanvas" width='800' height='800' border-radius= ></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

let circle = new Path2D();  // <<< Declaration
circle.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

context.fillStyle = 'lightblue';
context.fill(circle); //   <<< pass circle to context

context.lineWidth = 10;
context.strokeStyle = '#000066';
context.stroke(circle); 

(function() {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);

function onKeyDown(event) {
  var keyCode = event.keyCode;
  switch (keyCode) {
    case 68: //d
      keyD = true;
      break;
    case 83: //s
      keyS = true;
      break;
    case 65: //a
      keyA = true;
      break;
    case 87: //w
      keyW = true;
      break;
  }
}

function onKeyUp(event) {
  var keyCode = event.keyCode;

  switch (keyCode) {
    case 68: //d
      keyD = false;
      break;
    case 83: //s
      keyS = false;
      break;
    case 65: //a
      keyA = false;
      break;
    case 87: //w
      keyW = false;
      break;
  }
}

//neccessary variables
var tickX = 10;
var tickY = 10;

var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;

//main animation function
function drawStuff() {
  window.requestAnimationFrame(drawStuff);
  var canvas = document.getElementById("myCanvas");
  var c = canvas.getContext("2d");

  c.clearRect(0, 0, 800, 800);
  c.fillStyle = "lightblue";
  c.fillRect(tickX, tickY, 100, 100);

  if (keyD == true) {
    tickX += 1;
  }
  if (keyS == true) {
    tickY += 1;
  }
  if (keyA == true) {
    tickX--;
  }
  if (keyW == true) {
    tickY--;
  }
}
window.requestAnimationFrame(drawStuff);
</script>

Answer №1

I made some updates by relocating the circle code into the drawstuff function where it needs to be executed, and eliminated the use of fillRect.

Check out the outcome below:

(function() {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);

function onKeyDown(event) {
  var keyCode = event.keyCode;
  switch (keyCode) {
    case 68: //d
      keyD = true;
      break;
    case 83: //s
      keyS = true;
      break;
    case 65: //a
      keyA = true;
      break;
    case 87: //w
      keyW = true;
      break;
  }
}

function onKeyUp(event) {
  var keyCode = event.keyCode;
  switch (keyCode) {
    case 68: //d
      keyD = false;
      break;
    case 83: //s
      keyS = false;
      break;
    case 65: //a
      keyA = false;
      break;
    case 87: //w
      keyW = false;
      break;
  }
}

//necessary variables
var tickX = 10;
var tickY = 10;

var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;

//main animation function
function drawStuff() {
  window.requestAnimationFrame(drawStuff);
  var canvas = document.getElementById("myCanvas");
  var c = canvas.getContext("2d");

  c.clearRect(0, 0, 200, 200);
  
  let circle = new Path2D();  // <<< Declaration
  circle.arc(100 + tickX, 100 + tickY, 70, 0, 2 * Math.PI, false);

  c.fillStyle = 'purple';
  c.fill(circle); //   <<< pass circle to context

  c.lineWidth = 10;
  c.strokeStyle = '#000066';
  c.stroke(circle); 

  if (keyD == true) {
    tickX += 1;
  }
  if (keyS == true) {
    tickY += 1;
  }
  if (keyA == true) {
    tickX--;
  }
  if (keyW == true) {
    tickY--;
  }
}
window.requestAnimationFrame(drawStuff);
Focus this area, then use keys <b>d, s, a, w</b><br />
<canvas id="myCanvas" width='200' height='200' style="border: 1px solid #f4f4f4" ></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with my jQuery Ajax call, need some help

I am attempting to create an ajax request that will update the content of my select element. Below is the code for my request : $(function() { $("#client").change(function() { type: 'GET', url: "jsonContacts. ...

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

Adjust the value of a select box to the chosen option using JQuery

Could someone please assist me with this code? I am trying to adapt it for use on my mobile device with jQuery Mobile. var obj = jQuery.parseJSON(finalresult); //alert(obj); var dept = '2'; $(document).ready(function () { //$("#opsContactId ...

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

Determine the card type based on the card number

My array of card types is structured like this: var cards = new Array(); cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true}; cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4917,4913", checkdigit: tr ...

Selectors for fake elements and neighboring siblings

I'm struggling to show my menu when the toggle checkbox is selected. I know that my .menu-container is not a sibling of the toggle element, but I'm not sure how to make it work without moving the toggle outside of the div so that .menu-container ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

Incorporate new markers into Google maps without the need to constantly initialize the map

My current goal is to have the user input a latitude and longitude into a text box, and then display a marker on the map for that location without needing to reinitialize the map each time. To start, I have set up my map like this: <script type="text/ ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

Tips for preventing conflicts between variables and functions in JavaScript (no need for a jQuery plugin)

How can I prevent variable and function conflicts in Javascript without relying on jQuery plugins? I am interested in creating my own functions but want to avoid conflicts. I believe using function scope, where functions are used solely for the purpose of ...

Using Angular directives to pre-select a default option

I am currently working on a select HTML tag with two options, and I want to set the first option as the default choice. My select element includes Angular directives like ng-change and ng-model. I have attempted to achieve this by adding selected = "select ...

Buffering ceases on the video

I am experiencing an issue with 4 videos and a preloader, which should hide once all the videos are fully buffered. <div id="preload"> <h1> Download... </h1> </div> <video preload="auto" class= ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...

Automatically refresh a table within a webpage with updated database information without the need to manually refresh the

I'm a beginner in PHP and AJAX. The issue I am currently encountering is displaying a table on a JSP page and wanting to auto-update the table without refreshing the page every 10 seconds. I retrieve values from a database using a PHP page Below is t ...

Modifying an Object within a for-in loop

Hi there, I'm facing a challenge with updating an object that has child properties in my Angular application. Here is the initial object: $scope.osbStep = { test0Nav : { current : false, comp ...

Exploring Node.js with a straightforward illustration and tackling the EPERM error

const server = require('http').createServer(function(req, res){ }); server.listen(8080); This code snippet is causing an error to be displayed in the console: $ node node_server.js node.js:201 throw e; // process.nextTick error, or &apos ...

When the enter key is pressed on a child modal dialog, it triggers the enter action on the parent modal dialog in IE11 and

Having two bootstrap modal dialog windows, where one creates the other, is causing a problem. When the enter key is pressed on the child's text input, it triggers an event on the parent as well. If the last focused button on the parent was the one to ...

Arrangement of cards in a column

As someone who is new to working with CSS, Wordpress, and similar technologies, I am seeking assistance. I am struggling with creating card layouts. My goal is to achieve a layout similar to this, where the cards are displayed in two columns instead of ju ...

Struggling with ensuring that Angular-JS pauses and waits for an asynchronous call to complete before moving on

Understanding the use of promises in Angular for handling async operations is crucial, but I'm struggling to implement it effectively in this scenario. function fetchLineGraphData(promises){ var dataPoints = []; for (var i = 0; i < promise ...

Breaking down CSV rows and transforming numerical data (Typescript, Javascript)

Looking to convert a row from a csv file into an array and then transform the numeric values from string format. This represents my csv file row: const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323"; My objective is to create this array (with the ...