Canvas Delays in Clearing Background

It appears to be a straightforward issue, and I might just be missing something obvious. Here is the code snippet:

window.onresize = function(){
  init.canvas.width = window.innerWidth;
  init.canvas.height = window.innerHeight;
}
var init = {
  canvas: new Object(),
  ctx: new Object(),
  constructCanvas: function(){
    this.canvas = document.getElementById("canvas");
    this.ctx = this.canvas.getContext("2d");
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
  }
}
init.constructCanvas();

var a = 20;
var b = 20;
init.ctx.lineWidth = 4;
function loop(){
  init.ctx.fillStyle = "Blue";
  init.ctx.fillRect(0,0,init.canvas.width,init.canvas.height);
  init.ctx.moveTo(a,b);
  init.ctx.lineTo(a+=9,b);
  init.ctx.stroke();
}
setInterval(loop,100);

The expected behavior should result in smaller line segments of length 9 being drawn and cleared on each subsequent loop iteration, but currently, a single long line is continuously drawn, and the fillRect call does not seem to have any effect.

Answer №1

Here is a common issue with Canvas that arises when the beginPath() method is not used:

The canvas clears properly, but the path is never cleared, resulting in the entire line being redrawn instead of just the desired section. By using moveTo and lineTo, you are simply adding onto the existing Path, which is then displayed on stroke. To fix this, remember to start a new path each time:

function loop(){
  init.ctx.fillStyle = "Blue";
  init.ctx.fillRect(0,0,init.canvas.width,init.canvas.height);

  init.ctx.beginPath():
  init.ctx.moveTo(a,b);
  init.ctx.lineTo(a+=9,b);
  init.ctx.stroke();
}

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

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

Is there a way to locate a specific word within a sentence using JavaScript

I have these lists of answers: For example: const answerList = [{index: 2, answer: nice}, {index: 5, answer: sunday} ...] similar to that Also, I have a sentence: For instance: "hi i'm theo nice to meet you. how are you" My goal is to identify ...

Determining the quantity of items in a MongoDB collection using Node.js

Having recently delved into Node.js and MongoDB, I find myself struggling to grasp the concept of callbacks. Despite reading several articles, the topic remains confusing to me. In the snippet of code below, my aim is to retrieve the count of orders with s ...

Transferring Arrays from PHP Script to JavaScript Script

Can someone help me figure out how to pass an array from my PHP file to a JavaScript file? Here is the array I have: $pictures = array( "1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"), ); In my JavaScript file, I ...

Utilizing Nginx to Reverse Proxy to Node.js and Implement Rewrites

I have various applications running in the background behind an Nginx reverse proxy. One of these applications is a Node server using Express.js. I am forwarding domain.com/demo/app/<path> to localhost:7003/<path> through this Nginx configurati ...

Is there a way for me to figure out if a Primefaces RadioCheckbox has been selected?

Despite the numerous examples available on how to count checked checkboxes, I am facing difficulties in getting it to work. My goal is to enable a button when at least one checkbox is checked on the page, and disable it when none are selected. However, n ...

Is it permissible to access an iframe directly by its name?

I recently came across some JavaScript code that directly accesses an iframe by its name, without using getElementById() or any other method. Surprisingly, this code seems to be functioning properly in browsers like Chrome, Firefox, IE10, and Safari for Wi ...

Display only the posts of the logged-in user in a React application

I need assistance with a React return that displays only the posts of each logged-in user. Currently, my code loads all posts from all users and shows only the posts from the user who is currently logged in. However, the other posts still take up screen s ...

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

Using either AngularJS's simple .then method or the $q service to handle asynchronous requests

I'm trying to understand the distinction between AngularJS $q service and simply using .then() after an asynchronous request. For example, using .then(): function InboxService($http) { this.getEmails = function getEmails() { return $http.get(& ...

once an image begins to delete upon clicking, it will continue indefinitely

After creating a button and adding Math.floor(Math.random() * 2 + 1) to generate random correct and wrong answers, you also included 5 images as life counters. When a wrong answer is chosen, one of the images is supposed to be hidden or removed. However, t ...

Using jQuery to replace the value of a button with a variable string that has been concatenated

I am facing a dilemma with a button on my webpage. The value displayed on the button is a combination of variables and strings, like so: $('#btn1').attr('value','question'+currid+'ans1').button('refresh'); ...

Find similarities and differences between two CSV files

Dealing with 2 large files, both exceeding 1 million rows: The first file contains only an md5 hash The second file contains pairs of md5 and email addresses My task is to compare these two files and if the md5 hashes match, write the corresponding emai ...

Managing single sign-out with SSO using the Msal v2 library in a Node.js and Vue.js environment

The challenge: When using msal v2, logging in to the app via a Microsoft account saves parameters to the sessionStorage. Everything works perfectly until the user logs out on Office.com or any other site using Microsoft SSO. The problem arises because the ...

extract information from local storage using AngularJS

I'm having trouble getting the filter to work in my AngularJS project with local storage. Even though there are no errors, nothing happens when I type words into the input field. Can someone lend a hand? :) html: <div ng-app="myApp" ng-controller ...

Implementing VisualCaptcha with AngularJS and slimPHP in a RESTful manner

I am currently using AngularJS on the frontend and SlimPHP on the backend with REST URLs. In an attempt to integrate VisualCaptcha, I followed the instructions on the PHP side and verified that it works. I have a simple Angular dataService that fetches t ...

Iframe Loading at Lightning Speed

I have set up a script to load my iframe, but I noticed that the script loads the iframe content too quickly. Is there a way for me to configure it to preload all CSS images and content in the background before showing the full iframe content? Here is my ...

Avoiding a browser becoming frozen during an AJAX call

I'm currently working on sending a request when a user closes the page using the onbeforeunload event. This event triggers when the tab is closed or the page is refreshed. Here's my event implementation: window.onbeforeunload = function() { ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Having trouble resolving an error while attempting to incorporate an npm module into a vanilla JavaScript application

I admit my lack of expertise in building modern JavaScript apps is becoming evident. Currently, we have a Capacitor app that uses plain JavaScript without any build tools, and it functions well. Our goal is to incorporate Microsoft Code Push support throu ...