Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left.

I attempted to use control statements like "if," but unfortunately it did not work as expected.

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

var img = new Image();
img.src = "img1.png";
var speed = 0;
var xpos = 800;
var CXpos = 0;  //changing xpos
var result = Math.floor(Math.random() * 500) + 1;

function icon(){
    ctx.beginPath();
    speed -= 1;
    CXpos = xpos + speed;
    ctx.drawImage(img, CXpos, result, 60, 60);
    if(CXpos == 50){
        canvas.width = canvas.width;    //Is this the correct code?
        draw();
    }
    ctx.closePath();
}

function iconypos(){
    var num = Math.floor(Math.random()*100)+1;
    return num;
}

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    icon();
}

setInterval(draw, 10);

Answer №1

It appears that you are searching for a way to reset the speed variable back to its initial value of 0.

You do not have to re-call the icon() function because it will be triggered again by the next tick in the interval.

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

var img = new Image();
img.src = "https://avatars2.githubusercontent.com/u/15933454?s=60&v=4";
var speed = 0;
var xpos = 800;
var CXpos = 0;  //changing xpos
var result = Math.floor(Math.random() * 500) + 1;

function icon(){
    ctx.beginPath();
    speed -= 1;
    CXpos = xpos + speed;
    ctx.drawImage(img, CXpos, result, 60, 60);
    if(CXpos == 50){
        speed = 0;    // Unsure if this is correct?
        //icon();
    }
    ctx.closePath();
}

function iconypos(){
    var num = Math.floor(Math.random*100)+1
    return num;
}

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    icon();
}

setInterval(draw, 10);
<canvas id="Canvas" width="800" height="350"></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

Encountering a 403 Forbidden error while attempting to access a website built with Next.js

Every time I try to access the Next.JS website that's been deployed on IIS using the HTTP address, I'm faced with this error message: Get http://...../_next/static/chunks/webpack-73760e2208a549db.js net:: ERR_ABORTED 403 (Forbidden) However, w ...

Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here $(document).ready(f ...

Text field auto-saving within an iFrame using localStorage is not functioning as expected

My goal is to create a rich text editor with an autosave feature using an iframe. Although each code part works individually, I am struggling to combine them effectively. View LIVEDEMO This graphic illustrates what I aim to accomplish: The editable iFram ...

Employing Ajax for interacting with a database

I am attempting to query my database using a JavaScript function for the first time, and I am struggling to get it to work. While unsure if this is the correct approach, it is the one that I have come across. Below is a simple snippet of my HTML code: < ...

How to retrieve the value of a hidden field in ASP.NET after a partial postback

On my ASP.NET page, I am encountering an issue with a hidden field not being found during an asynchronous postback within an update panel. In the updatepanel_Load event, the following code is used: if (!IsPostBack || triggeredRefresh.Value == "1") { H ...

Storing values in localStorage with a specific format can be accomplished by following these steps

How can I save a localStorage value with special characters? I currently have the following value: ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew but when I try to store it, it appears as if there is an arrow indicating that the value can be ex ...

Create Joi Schema based on TypeScript types/interfaces

Searching for a way to convert Typescript types or interfaces into joi schema objects led me to various solutions that did the opposite, such as generating Typescript types/interfaces from joi schemas. I came across options like ts-interface-builder and ts ...

Enter information into the designated text field once you have selected the button

In my PHP/HTML form for user login, I have a password field where users can enter their password or click a button to generate a random one. Although I found some JavaScript code online for this feature, I'm having trouble getting it to work with my ...

Why does the header still show content-type as text/plain even after being set to application/json?

When using fetch() to send JSON data, my code looks like this: var data = { name: this.state.name, password: this.state.password } fetch('http://localhost:3001/register/paitent', { method: 'POST&a ...

Next.js project encountered a TypeError with message [ERR_INVALID_ARG_TYPE]: The "to" argument is expected to be a string type

While working on a Next.js application, I came across a TypeError that is linked to the undefined "to" argument. This issue pops up when I launch my development server using npm run dev. Despite checking my environment setup and project dependencies, I hav ...

Hovering over a table cell triggers a popup in Angular

Inserted a class into <td><span class="only-show-on-hover"></span></td> CSS code for the class td span.only-show-on-hover { visibility: hidden; } td:hover span.only-show-on-hover { visibility: visible; } Code for dialog box < ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Tips for utilizing the loadDataWithBaseURL() method to load CSS and JS files directly from an SDCARD

I am facing an issue with loading files from SDCARD onto a webview. The .html, .js, .css files are stored on the SDCARD in my scenario, and the html file content is encrypted. The steps I follow to load the html file are: Read file content Decrypt all co ...

Harness the power of a NUXT component on a different website

Currently, I have a fully functional NUXT application that consists of numerous pages and components operating in `universal` mode. My challenge now is to render one of these components on a separate static HTML website. Exporting a component from a stand ...

What is the best way to eliminate blank values ("") from an array?

I am working with a two-dimensional array that was generated from an HTML table using jQuery, but I have noticed that some values are empty and are displaying as "". How can I go about removing these empty values from the array? <table> ...

Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location. For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be associated with 000 - TTT PARAMET ...

Facing issues with ReactCSSTransitionGroup as transitionAppear feature is not functioning

I'm having trouble with the appearance and disappearance of notifications. The transitionAppear property doesn't seem to be working as expected. I'm adding the notification popup item to the onBlur event. The animation for the leave event wo ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Adaptable Semantic UI form design

Welcome, internet friends! If anyone out there has a moment to spare and is familiar with Semantic UI, I could really use some assistance... Currently, I am working on a form that looks great on larger screens like this: https://i.stack.imgur.com/cafc5.j ...

Exploring GLTF models with Threejs - just a click away!

I am currently developing a project in three.js where I aim to load a GLTF file consisting of geometric shapes. My goal is to extract information, specifically the name, of the shapes that are clicked within the GLTF file. At this stage, I am using console ...