The dimensions of the canvas are directly impacting the stretching of the Sprite

I am currently working on a small program to render sprites with 2D transformations. You can find the project here. The issue I am encountering is that when trying to render a 100px by 100px square, it ends up being stretched into a rectangle shape. I have tried to pinpoint the problem in my code but so far, I have been unsuccessful. Here are some relevant excerpts:

const position = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, position)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  -w/2,  h/2,
   w/2,  h/2,
  -w/2, -h/2,
   w/2, -h/2
]), gl.STATIC_DRAW)

 

gl.bindBuffer(gl.ARRAY_BUFFER, position)
gl.vertexAttribPointer(attrib.vertexPosition,
                      2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(attrib.vertex)

 

gl.uniformMatrix2fv(uniform.transformMatrix, false, transform)
gl.uniform2f(uniform.translation, x+w/2, y+h/2)
gl.uniform2f(uniform.screenRes, gl.canvas.width, gl.canvas.height)

Vertex shader:

attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;

uniform mat2 uTransformMatrix;
uniform vec2 uTranslation;
uniform vec2 uScreenRes;

varying vec2 vTextureCoord;

void main() {
  gl_Position = vec4(2.0 * (uTransformMatrix * aVertexPosition + uTranslation) / uScreenRes - 1.0, 1.0, 1.0);
  vTextureCoord = aTextureCoord;
}

Feel free to experiment with the variables in the pen, especially adjusting the canvas dimensions; changing one dimension affects the scaling of the sprite in the opposite dimension.

P.S. Please note that for now, I am not concerned about the texture inversion issue. I will address that at a later stage.

Answer №1

While your code is accurate, don't forget to define the viewport settings. Make sure to add this line before any draw calls (especially after gl.clear())

gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)

The WebGLRenderingContext.viewport() function in the WebGL API establishes the viewport, detailing the transformation of x and y from normalized device coordinates to window coordinates.

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

The visual symbol is not being shown on the selection box in Mozilla Firefox

I've encountered an issue with a checkbox I created to display a + and - for expand and collapse functionality. HTML Code: <input type=checkbox class="ins" ng-model=show ng-class='{open:show}'><b>Show</b> CSS code: .ins ...

The hyperlink element has been added but is not clickable

I'm attempting to incorporate a download feature into my webpage using Greasemonkey. Despite successfully adding the new div element to the page, I am encountering an issue where the download window does not open as expected. var iDiv = document.crea ...

Error: The request to /api/auth/login in Postman failed unexpectedly

As I am working on developing an app using node.js and express, I encountered an error while making post requests in Postman. Cannot POST /api/auth/login%0A Below are the details of my app's structure along with the files involved: app.js const ex ...

Guide to turning off the Facebook iframe page plugin

I am facing a challenge with embedding a facebook iframe on my website. I want to disable it once the screen width reaches a specific point, but I am struggling to make the iframe disappear properly. Here is how I have attempted to implement this: window.o ...

Ways to programmatically append data to an object using JavaScript

My dilemma involves an object: var myObject={}; accompanied by a function that appends values to the object: function appendData(id, name){ //logic to validate id and name format, specify conditions for name being "John" and id being "I23423" my ...

Guide to extracting a specific segment from req.body in Node.js

I've been attempting to access a specific nested property of req.body, but the output always turns out to be undefined. Here is the code snippet: let dataReceived = JSON.stringify(req.body); console.log(dataReceived); let refCode = ...

Issue: Database not updating after input via AJAXExplanation: Despite submitting new data through AJAX, the

I've been struggling to display the UPDATED database on my initial html page after submitting new information. Despite successfully updating the database using AJAX, I can only see the outdated version. Any assistance in resolving this issue would be ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Set up a JavaScript function that triggers an alert if two numbers are determined to be equal

I created a code snippet that should display an alert message when a button is clicked, indicating whether two random numbers generated are equal or not. The random numbers must be integers between 1 and 6. I implemented this functionality in JavaScript bu ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Trigger a function on q-select change using onChange event (Quasar Framework)

I'm trying to get the function to run when I change the selected value, but it's not working. How can I solve this issue? Below is the code I am using: <q-select v-model="single" :options="['def', 'abc', ...

Tips for excluding specific elements when clicking on a document

JavaScript $(document).click( function () { alert("Hello there"); } Web Development <div id="wrapper"> <div id="inner-1"> <div id="sub-inner1">Sub Inner1 Content</div> <div id="sub-inner2">Sub Inner2 Content&l ...

Improving the Performance of DisplayField Binding in ExtJS 5

When I trigger a window to create a new item, there is a noticeable lag when passing in the record for the bound fields. The record is essentially a blank one with default values provided by the framework. In this demo, there are 3 buttons: The first but ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Utilizing Think ORM seamlessly across multiple files without the need to repeatedly establish a connection to the

I'm facing a situation where I have numerous models for thinky, and in each file I am required to create a new object for thinky and connect it multiple times due to the high number of models. var dbconfig = require('../config/config.js')[& ...

Ways to extract the coordinates for slices positioned around the circumference of a pie chart

Currently, I am working on designing a pie chart with D3 using d3.layout.pie(). The image resembles the one displayed below, but without the black dots. These dots were added manually in Photoshop to highlight an issue that I am facing. I am curious about ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

What is the method for verifying a password in the login process when it has been hashed by bcrypt during registration?

Currently in the process of developing a signup and login page using Node.js with Pug, Mongoose, and bcrypt. I am encrypting and storing passwords in the database after registration or sign up. I'm facing an issue with the comparison function as it r ...

Receiving a positive server response without needing to trigger the Ajax route in a NodeJs/Express application

Setting up the login route: app.use('/login', require('./routes/login')); The 'login' module includes the route to display the login HTML page and validate the login using an Ajax call. var router = require('express&ap ...