Interactive canvas box in motion with directional arrows

I am attempting to create a basic canvas box that moves using arrow keys. Here is the code:

Here's the code snippet:

$(function() {
  var n = 3;
  var xD = 0;
  var yD = 0;

var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  var ss = {
    "x": 0,
    "y": 0,
    "width": 100,
    "height": 75
  };

  function render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.rect(ss.x, ss.y, ss.width, ss.height);
  ctx.lineWidth = 1;
  ctx.strokeStyle = "black";
  ctx.stroke();
  }

  function move() {
x = ss.x + (xD * n);
y = ss.y + (yD * n);
    ss.x = x;
    ss.y = y;
}

  $(document).keydown(function(e) {
xD = e.which == 37 ? -1 : xD;
xD = e.which == 39 ? 1 : xD;
yD = e.which == 38 ? -1 : yD;
yD = e.which == 40 ? 1 : yD;
e.preventDefault();
});

  $(document).keyup(function(e) {
xD = e.which == 37 ? 0 : xD;
xD = e.which == 39 ? 0 : xD;
yD = e.which == 38 ? 0 : yD;
yD = e.which == 40 ? 0 : yD;
e.preventDefault();
});

  render();
  setInterval(move, .01);
});
body {
margin: 0;
}

#canvas {
border: 1px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>

This script should enable the following functionalities:

  • Moving the box by pressing arrow keys
  • Adjusting canvas dimensions to width = "100vw" and height = "100vh"

Answer №1

To ensure that the canvas renders the new position after every move, make sure to include the render method as the last line of your move method. This way, the render method will be called each time the object moves.

function move() {
    x = ss.x + (xD * n);
    y = ss.y + (yD * n);
    ss.x = x;
    ss.y = y;
    render(); // Make sure to add this line
}

Answer №2

Give this method a try: click on the result screen and then use your keyboard's arrow keys. If this solution works for you, please mark it as the answer. Feel free to leave a comment if you need any further assistance.

var canvas;
var ctx;
var dx = 5;
var dy = 5;
var x = 150;
var y = 100;
var WIDTH = 300;
var HEIGHT = 200;

function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}

function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}

function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}

function doKeyDown(evt){
switch (evt.keyCode) {
case 38:  /* Up arrow was pressed */
if (y - dy > 0){
y -= dy;
}
break;
case 40:  /* Down arrow was pressed */
if (y + dy < HEIGHT){
y += dy;
}
break;
case 37:  /* Left arrow was pressed */
if (x - dx > 0){
x -= dx;
}
break;
case 39:  /* Right arrow was pressed */
if (x + dx < WIDTH){
x += dx;
}
break;
}
}

function draw() {
clear();
ctx.fillStyle = "white";
ctx.strokeStyle = "black";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "purple";
circle(x, y, 10);
}

init();
window.addEventListener('keydown',doKeyDown,true);
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Test</title>
</head>
<body>
<section>

<div>
<canvas id="canvas" width="300" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>    

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

What is the best way for AngularJS ng-repeat to access the key of an item?

For more information, check out the documentation: https://code.angularjs.org/1.2.26/docs/api/ng/directive/ngRepeat The ngRepeat directive creates a template for each item in a collection. Each template has its own scope with the current item assigned t ...

What is the best way to show two icons next to each other within a React component?

For my school project, I am working on developing an app and encountering a challenge. I have been trying to display two icons side by side on a screen using React (I've been learning React for 5 months but still consider myself a beginner). However, ...

Embrace AngularJS: Employ the ".then" method and retrieve the response

In order to send a http request and receive the response of this request, I am trying to implement a mechanism where if the data is successfully saved, I can retrieve database information, and if it fails to save, I can track errors. To achieve this, I pla ...

The $OnChange function fails to activate when passing an object by reference

Hi there, I've encountered a problem in my code that I'd like some help with. In my example, I have two components: Parent Component and Child Component. Both components share a field called rules. The Parent Component passes the rules field to ...

Is there a way to refresh my order hook in React JS?

I've been attempting to modify the values within my order hook, but for some reason, they aren't updating. I'm relatively new to React and can't figure out what mistake I might be making. Any insights? Take a look at my code snippet: ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

Is it possible to change the time format from one to another in javascript using moment.tz?

I've experimented with multiple approaches, but I'm struggling to transform a date like 1640638800 into the 2022-11-27 16:00:00 America/New_York timezone format using moment.tz in JavaScript. Here's the code I'm currently working with: ...

retrieve nodes from xml automatically

I am facing an issue with my JavaScript code where I need to extract all data from a specific node. I want to display all the nodes labeled 'ows_Person' on my website. Currently, I can only display one 'ows_person', but I need to iterat ...

Dynamically switch between showing more and showing less content on each div

Whenever the specific show more button is clicked, the content should be displayed without causing the entire component to re-render. I have tried using a useState, but each time the button is clicked, the whole component re-renders, resulting in long load ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

Adjusting Canvas Size in WPF

I have implemented a ResourceDictionary to manage all my icons as shown below: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

Unable to integrate bower with gulp for automation

I am trying to get gulp to run the installation of all files listed in my bower.json. However, despite writing the code below, it is not working and I'm not seeing any errors. What could be causing this issue? var gulp = require("gulp"); var bower = ...

Troubleshooting: Issue with append function not functioning properly after click event in Angular

I am struggling to implement a basic tooltip in AngularJS. Below is the HTML I have: <span class="afterme" ng-mouseover="showToolTip('this is something', $event)" ng-mouseleave="hideToolTip();"> <i class="glyphicon glyphicon-exclama ...

Displaying a relative div on mouse hover over an HTML tag using React

In the section below, you will find the code snippet... <ul className="no-style board__list"> {Object.keys(today.books).map(function(id) { var refBook = today.books[id][0]; return ( ...

Check if array2 is partially ordered as array1 in JavaScript

Is there a more efficient way to achieve these conditions in JavaScript using vanilla or lodash? const array1 = [1, 2] const array2 = [1, 2, 3, 4] //true const array2 = [1, 3, 2, 4] //true const array2 = [4, 3, 2, 1] //false const array2 = [2, 3, 1, 4] / ...

Exceljs : 'An issue has been identified with certain content in the document named "file.xlsx"(...)'

I have encountered an issue with an xlsx file generated using Exceljs. While I have been creating csv files in my project without any problems, creating an xlsx file now poses an error. The xlsx file opens clean on Ubuntu/LibreOffice Calc, but there is an ...

Tips on preventing duplicate websocket clients in VueJS

Each time I access a component, it triggers the socket.on event. Additionally, there is a Vuejs button component as shown below. So when I emit to the 'socket.on('voice')' event in nodejs, the nodejs socket emits to the 'socket.on( ...

AngularUi Mobile Modal List Display

I attempted to implement the code from 32400236/dynamically-generate-modals-with-mobileangularui but encountered issues. I also tried using the following: <div class="access-item" ng-repeat="item in items track by $index"> <a ui-turn-on="$index" ...