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

Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...

Using Backbone: Leveraging a custom extended model when fetching a collection

Currently, I am working on developing a custom Wordpress theme using technologies like Javascript, Requirejs, and Backbonejs. As part of this process, in the index route, I have set up a new postsCollection app.postsCollection = new Posts.Collection(); to ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

Prevent redundant Webpack chunk creation

I am currently working on integrating a new feature into my Webpack project, and I have encountered a specific issue. Within the project, there are two entry points identified as about and feedback. The about entry point imports feedback, causing both abo ...

Injecting dynamic content using JavaScript

My goal is to develop a web page where clicking on any of the three images will cause the content to be inserted into the empty div located above the image links. Below is the JavaScript code I'm using: <script type="text/javascript" src="js/jque ...

Is there a way to adjust the font size in Javascript/Html without changing the color?

I have a code snippet that creates a button to increment a variable, and I want to change the font size of the displayed variable. This code is for a game akin to cookie clicker. <div class="game-object"> <script type="text/javascript>"; var c ...

Using JavaScript parameters in a HTML document

I am trying to replicate a page similar to this. The issue I am facing is the inability to use external JS files in ASP.net (as far as I know). Therefore, I am defining the functions and attempting to utilize them within the HTML page instead. <%@ P ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

What is the process for dynamically altering the source file of VueRouter?

Hello, I am working on a project that involves multiple roles using VueJs and Laravel. Laravel is used as the back-end while Vuejs serves as the front-end. The project has three different roles: User, Modirator, and Editor. Here is a snippet of my code ...

Having trouble using a setTimeout() callback to display a Bootstrap Vue modal programmatically

I am currently working on a Vue CLI application (using the Webpack template) that utilizes Bootstrap Vue for displaying modal windows. In my Vue component's mounted() hook, I am attempting to programmatically show the modal by referencing the Bootstra ...

Sequelize throwing Javascript heap out of memory error when inserting large files into database

I have successfully converted an excel file to MySQL on my local machine. However, when I try to do the same with larger files on a container limited to 2048MB of memory, it doesn't work. I attempted to increase the memory limit using node --max-old-s ...

Basic AngularJS application, however I am receiving {{this is supposed to be the information}}

Building an angularjs app I have set up an asp.net mvc4 application and integrated the angularjs package using nuget. The Layout.cshtml file has been updated to look like this: <!DOCTYPE html> <html ng-app="myApp"> <head> <meta ...

Understanding the mechanics of utilizing node modules and requiring them within an Express 4 router

After initiating a node project using an express 4 generator, I have set up the following routing code in the /routes/index.js file: // ./routes/index.js var express = require('express'); var router = express.Router(); router.get('/' ...

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

Troubleshooting: Issues with URL redirection on localhost using Node.js

I've developed a service to verify if the user is logged in, but I'm encountering difficulties running the code on localhost. What could be causing this issue? The redirection isn't functioning as expected, should the code for redirecting t ...

Customizing the "added to cart" message in Woocommerce and setting up a notification system for customers

My main focus is on customizing the Woocommerce notation system for a personalized shopping cart experience. After some research, I stumbled upon a very helpful user response which suggested modifying the message by adding the following code snippet to th ...

What is the best way to create floating text that appears when clicked, similar to the mechanics

https://i.stack.imgur.com/nRKG1.jpg Upon clicking the "big cookie" in my game, a popup appears displaying the number of cookies earned (like +276.341 septillion in this image). The popup slowly moves upward and then fades out. I successfully incorporated ...

Submitting data using JavaScript's POST method

I am facing a challenge with posting Array data to an HTTP connector. My data is structured as follows: var data = [{ key:'myKey', keyName:'myKeyName', value:'value', valueName:'valueName' }, { ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...