Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck.

I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document. I've attempted some coding (link to jsFiddle), but I'm struggling to make progress. Any guidance or advice would be greatly appreciated.

var can, ctx, step, steps = 0,
  delay = 20;

function init() {
  can = document.getElementById("MyCanvas1");
  ctx = can.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.font = "20pt Verdana";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  step = 0;
  steps = can.height + 50;
  RunTextRightToLeft();
}

function RunTextRightToLeft() {
  step++;
  ctx.clearRect(0, 0, can.width, can.height);
  ctx.save();
  ctx.translate(can.width / 2, step);
  ctx.fillText("Welcome", 0, 0);
  ctx.restore();
  if (step == steps)
    step = 0;
  if (step < steps)
    var t = setTimeout('RunTextRightToLeft()', delay);
}
canvas {
  border: 1px solid #bbb;
}
.subdiv {
  width: 320px;
}
.text {
  margin: auto;
  width: 290px;
}
<body onload="init();">
  <div class="subdiv">
    <canvas id="MyCanvas1" width="300" height="200">
    </canvas>
  </div>
</body>

Appreciate your help!

Answer №1

Looking to bring words to life in your sentences? Here's a neat way to animate them:

Check out this guide on animating words

Start by defining word objects within an array:

var words=[];

words.push({
    text:'Hello',
    // starting x,y coordinates offscreen
    x0:Math.random()*cw,
    y0:(Math.random()*100)+ch,
    // final position of the word onscreen
    x1:20,
    y1:50,
    // font size
    size:10,
    // delay before animation starts
    delay:200,
    // percentage progress of animation
    pct:0
});

Determine where each word should end up to form a sentence:

var accumX=0;
for(var i=0;i<words.length;i++){
    w=words[i];
    // measure the word and assign its ending x1 value
    ctx.font=w.size+'px verdana';
    var width=ctx.measureText(w.text).width;
    w.x1=accumX;
    accumX+=(width+8);
    // calculate interim waypoints for animation
    w.dx=w.x1-w.x0;
    w.dy=w.y1-w.y0;
}

Now let's animate each word from its initial position [x0,y0] to its end point [x1,y1]:

var start=performance.now();
requestAnimationFrame(animate);

function animate(time){
    var countComplete=0;
    // clear canvas for new frame
    ctx.clearRect(0,0,cw,ch);
    for(var i=0;i<words.length;i++){
        var w=words[i];
        if(w.pct==100){countComplete++;}
        // calculate x,y waypoint based on percentage completion
        var x=w.x0+w.dx*w.pct/100;
        var y=w.y0+w.dy*w.pct/100;
        w.pct=Math.min(100,w.pct+1);
        // draw the animated text
        ctx.font=w.size+'px verdana';
        ctx.fillText(w.text,x,y);
    }
    // request another loop if animation is not complete
    if(countComplete<words.length){
        requestAnimationFrame(animate);
    }
}

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 function get_template_directory_uri() returned an unexpected string error

Exploring WP themes has been an interesting journey for me. Currently, I am working on creating a shortcode for some html/script and encountering an issue with enqueuing the js file. My initial query is about whether I am loading this from the correct loc ...

Ways to store AJAX response data for future use

I am struggling with implementing the getState function. My goal is to update a field on click using a state value retrieved from an AJAX call. I have come across mentions of promises in other responses, but I am unsure how to integrate them into my code ...

Struggling to make the upvoting feature function properly in the Thinkster MEAN Stack Tutorial

While following the MEAN Stack tutorial on this website, I decided to modify my code to utilize Controller as instead of using $scope as demonstrated in their examples. I am encountering an issue with the upvote functionality. Whenever I click to upvote a ...

What could be causing the lack of responsiveness in my font size when adjusting to different screen sizes?

My understanding was that using font-size: 4em; would result in a relative size, but I am facing an issue where the font size remains constant regardless of window size. This causes overlap and makes the text look unattractive. Specifically, the text in qu ...

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...

JQuery Function for Repeatedly Looping through Div Elements

I've been experimenting with creating a loop that alternates the fade-in and fade-out effects for different elements. This is what I have so far: setInterval(function() { jQuery(".loop").each(function(index, k) { jQuery(this).delay(1200 ...

Display and conceal specific table cells based on a user's search for a singular cell

I recently wrote a jQuery script to filter rows in a table based on user input. However, I encountered an issue with my current code when trying to search for a specific string within the table. Here's the scenario: a|b|c|d| e|f|g|h| i ...

The JavaScript code for summing two numbers is not functioning as expected

My HTML code takes a user input number, performs a calculation using a formula, and displays the output. The chosen input is inserted into the formula, and the result is added to the original number. However, there seems to be an issue with adding decimal ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...

What is the process for extracting the differences between two or three files and merging them together in Node.js?

Recently, I've been experimenting with webpack and successfully managed to output and transform es5 build to include nomodule in the tags directly from HtmlWebpackPlugin using hooks. Similarly, for the es6 build, I added type="module". Howe ...

Implement dynamic configuration injection by allowing users to specify the name of a configuration file during runtime, instead of having it fixed in the code

In my development using webpack, I am exploring ways to make my application configurations more dynamic. Presently, the project is a create-react-app that has been ejected. For instance, when creating a local build in my package.json file, I include the f ...

Ensure that the loop is fully executed before proceeding with any additional code

Check out this code snippet I've been developing: let arrayB = []; for (let index = 0; index < res.length; index++) { let fooFound = false; const dynamicFoo = require(`./modules/${res[index]}`); rest.get(Routes.applicationCommands("BLA ...

"Major issues arise as CSS3 Animation fails to function properly across all web

I have been experimenting with using a sprite and CSS3 animation to create a rollover effect. While it seems to be working in CODA 2, I'm encountering issues when testing in Mozilla, Chrome, Safari, and Opera as the animation fails to trigger. /*link ...

I am having issues with Tailwind CSS overriding the responsive padding on my website

I'm currently working on implementing responsive padding for a component. Given that Tailwind CSS follows a mobile-first approach, I have set the mobile padding to p-3, while screens at "md" and larger widths should use p-5. However, it seems like the ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

issue arising where the table's border is not displaying

I'm confused about why the border of the first tbody tr's td is not visible. https://i.stack.imgur.com/Fwlv7.png I can't see any reason why the border is not showing up. Here's what I've figured out: If the natural height of th ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

The flex container cannot contain all of the content due to an

I am looking to implement a flexbox dropdown menu similar to this: After researching online, I found a simple dropdown menu example. However, I want to customize it using flexbox and its properties. The issue I encountered is that the flexbox container do ...

Utilizing numerous instances of setInterval

I've created a jsFiddle which can be found here: http://jsfiddle.net/dztGA/22/ Main Objective: My aim is to have two independent timers on the same page that can be stopped and restarted either by hovering or manually. The Issue: The problem illustr ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...