Issue with HTML5 Canvas y-axis dimensions

I am attempting to create a basic animated HTML canvas with a moving block controlled by WASD keys. I encountered an issue where drawing a 5x5 rectangle appeared to be 5x10 on the canvas. Upon inspecting my code and logging the position of the element, I discovered that the X direction ranges from 1-300 while the Y direction is limited to 1-150, despite styling the canvas as 300x300. Can someone help me identify any mistakes in my implementation?

    <!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="script.js" defer></script>
</head>
<body>
    <div class="text-holder holder" id="instruction-holder">
        <p class="text" id="instruction">Use WASD to navigate around the viewer</p>
    </div>
    <div class="holder" id="canvas-holder">
        <canvas id="canvas"></canvas>
    </div>
</body>
</html>

and the css

    #canvas {
    width: 300px;
    height:300px;
    margin-left: auto;
    margin-right: auto;
    display: block;
    border-style: solid;
    border-color: grey;
    border-radius: 1px;
}

.holder {
    display: block;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

and the js

var UP = "87", DOWN = "83", LEFT = "65", RIGHT = "68", X = 10, Y = 5, XSIZE = 10, YSIZE = 5;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var xPos, yPos;

window.addEventListener("load",init);
document.addEventListener('keydown',move);

function init() {
    xPos = 1;
    yPos = 1;
    ctx.fillStyle = "black";
    ctx.fillRect(xPos,yPos,XSIZE,YSIZE);
}

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

function reDraw(delX, delY) {
    console.log(yPos+delY + " " + (xPos+delX));
    if (xPos+delX > 0 && xPos+delX < 300 && 
        yPos+delY > 0 && yPos+delY < 150) {
        clear();
        ctx.fillStyle = "black";
        xPos = xPos+delX;
        yPos = yPos+delY;
        ctx.fillRect(xPos,yPos,XSIZE,YSIZE);
    }
}

function move(ev) {
    var delX, delY;
    var key = ev.keyCode;
    if (key == UP) {
        delX = 0;
        delY = -Y;
    } else if (key == DOWN) {
        delX = 0;
        delY = Y;
    } else if (key == LEFT) {
        delX = -X;
        delY = 0;       
    } else if (key == RIGHT) {
        delX = X;
        delY = 0;
    }

    if (delX != undefined && delY != undefined) {
        reDraw(delX, delY);
    }
}

Answer №1

To ensure the proper sizing of the canvas element, you need to explicitly set its dimensions. If not specified, the default size will be 300x150. Keep in mind that CSS only scales the element, not the actual bitmap inside (the 300x150 bitmap gets stretched by the CSS rule to fit the screen, but its internal size remains unchanged):

<canvas id="canvas" width=300 height=300></canvas>

Make sure to remove these lines from your CSS:

#canvas {
  /* width: 300px; */
  /* height:300px; */
  ...

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

How does CSS affect the size and performance of a website?

Examining the content of this css file (focusing on the last 5 lines specifically): #page section .s_1 { overflow:hidden; width:435px; float:left;} #page section .s_1 h1 { font-size:36pt; color:#001744; line-height:1.1; margin-bottom:64px;height:107px;} # ...

Utilizing $routeParams to dynamically generate the templateUrl with AngularJS

Our platform offers a 2-level navigation system. We are looking to utilize AngularJS $routeProvider to dynamically load templates into an <ng-view />. Here is the approach I am considering: angular.module('myApp', []). config(['$route ...

Tips for concealing a parent element while inside a span with jquery

Beginner asking for help! Take a look at what I've coded: <div class="Links"> <a href="/testthis1.html" data-id="button1"> <img class="icon" src="/test1.png" alt="test1"> <span>Test 1</span> < ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...

Create a Vue application that is built on modules which could potentially be absent

I am currently developing a Vue+Vite app with module-based architecture. I have several Vue components and some parts of the app are functioning correctly. However, I want to ensure that the missing components are not imported or used in the application. H ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

Converting a Complex Array of Objects into a CSV File for Download in a React Application

My current data is available for download in xls/csv format, but when using the react-csv npm package, the name and description are being displayed in the same column instead of separate columns. I am seeking assistance on how to display the data with Nam ...

When using HLS with Media Source Extensions on mobile devices, the <video> element with the muted and autoplay attributes may freeze on the first frame

I recently added a background video to our website using mux.com. The video is set to autoplay with HLS, but Chrome requires Media Source Extensions for playback. To ensure the HTML5 video auto plays, I included the necessary mute parameters as well. How ...

Switch body class when the navbar's collapse show class is toggled

There are numerous methods to accomplish this task, but I am seeking the most optimal and efficient approach. My goal is to toggle a custom body class when the .navbar-toggle triggers the .show class on the .navbar-collapse element. I'm hesitant abo ...

Adjusting the color of the legend on a LineChart in ExtJS 4 on-the-fly

I've been trying to find information on how to modify the color of the x legend in a Line chart without success. Can anyone help me with this? I have included an image of the chart for reference. ...

What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my la ...

Another option could be to either find a different solution or to pause the loop until the

Is it possible to delay the execution of a "for" loop until a specific condition is met? I have a popup (Alert) that appears within the loop, prompting the user for confirmation with options to Agree or Cancel. However, the loop does not pause for the co ...

Scroll issue causing CSS not to be applied to a field within a div

Can someone help me with this issue I'm facing in my jsfiddle example? Here is the link: http://jsfiddle.net/AnnaMiroshnichenko/xjyb8/1/. The problem is, when I scroll the div, the field underneath the scroll does not appear to be applying CSS rules p ...

Using JavaScript to calculate dimensions based on the viewport's width and height

I have been trying to establish a responsive point in my mobile Webview by implementing the following JavaScript code: var w = window.innerWidth-40; var h = window.innerHeight-100; So far, this solution has been working effectively. However, I noticed th ...

Issue with Selenium WebDriver: Expectation failure while waiting for element visibility at specified location(..)

I'm facing a little issue with my automated test. Whenever the test encounters an error like this: Expected condition failed: waiting for visibility of element located by(...) I find it difficult to pinpoint the exact problem. @BeforeMethod pub ...

Tips on how to customize/ng-class within a directive containing a template using replace: true functionality

To keep replace: true, how can ng-class be implemented on the directive below without causing conflicts with the template's ng-class? This currently results in an Angular error: Error: Syntax Error: Token '{' is an unexpected token at co ...

drag items on your smartphone with ease

Hello everyone, I am looking to make items draggable on a smartphone as well. Here is my HTML code: <input class="inputText mb-2 border border-primary rounded" v-model="newTodo" @keypress.13='addTodo' placeholder="W ...

Setting references to child components with VueRouter in Vue

I've written the following code snippet in my main.js file for my Vue web application: const routes = { name: "Main", path: "/main", redirect: "/main/home", component: MainComponent, children: [ { path: &quo ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Loading 500,000 entries individually into mongodb results in a memory overflow

I am currently working on inserting a large volume of 500,000 records into a MongoDB collection. These records are stored in a CSV format, parsed, and then saved to an array. I am using a recursive function to insert the records one by one, and when a reco ...