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

Creating margin on a canvas with jsPDF is a simple task that can be accomplished

Hi there, I'm currently working on generating a PDF from HTML using jsPDF, but I've run into an issue with setting page margins. I would really appreciate any assistance on how to add margins to my pages using the canvas object. Below is the sou ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Discover the art of utilizing two distinct binding strings, wherein upon the selection of either, the alternate binding string shall automatically be

Having to use two different bindingstrings is a requirement due to a tool used for creating PDFs. My objective is to have the corresponding bindingstring turn "Off" when a user clicks on either the Yes or No button, and have the clicked button turn to "Yes ...

Error during minification process for file opentok.js at line 1310: react-scripts build

I encountered an error while trying to minify the code in my React project using npm run build. The snippet below seems to be the cause of the issue. Any suggestions on how I can resolve this problem? const createLogger = memoize(namespace => { /** ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Automatically generate the first user on the Parse Server system

Is it feasible to programmatically create a User on Parse server without the need for sign up? More information can be found at https://github.com/parse-community/parse-server We attempted this using cloud code. var user = Parse.User(); user.setUserna ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Having trouble locating the objects in the parent scope of an Angular directive

My custom directive needs to access the object $scope.$parent.users. When I use console.log $scope.$parent: myDirective.directive('scheduleItem', function(){ return { restrict: 'EA', link: function($sco ...

Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe: 1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared c ...

Transforming a React Class Component into a React Functional Component

After struggling for a day with multiple failed attempts, I have been unsuccessful in converting a React Class Component. The original class component code is as follows: class NeonCursor extends React.Component { constructor(props) { super(props); ...

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

Adjust the top margin of content to account for the height of a fixed header

When dealing with a fixed header that has been removed from the HTML flow, it can be tricky to adjust the content below it. The challenge arises because the height of the header can vary based on screen size. How can we dynamically adjust the margin-top fo ...

Tips for showcasing the Phaser game screen exclusively within a React route

I am trying to make sure that my game screen only appears on the '/game' route. However, when I initialize it using the method "new Phaser.Game(config)", it ends up displaying on every route including '/home', the default route '/& ...

jQuery fadeIn effect happening at rapid speed

I am currently working on integrating ajax with WordPress. After the ajax call is completed, I am successfully fading out a specific div slowly. However, when trying to fade in the new data using jQuery's fadeIn() method, I noticed that regardless of ...

All browsers experiencing issues with autoplay audio function

While creating an HTML page, I decided to include an audio element in the header using the code below: <audio id="audio_play"> <source src="voice/Story 2_A.m4a" type="audio/ogg" /> </audio> <img class= ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...

Is Ursina the right choice for web development?

Looking for a method to compile Ursina for HTML5 using WebAssembly or another technology? I am seeking to make my Ursina Game compatible with Linux & Mac (and potentially Android/iOS with webview), but the current cross-platform compilation options for Py ...

When the mouse leaves the area, I would like the iframe within the div to be refreshed

When you hover over the button on the right, a slide panel appears with an iframe. Each time this page loads, it has a different background. I want a new background to load every time there is a new hover, requiring a refresh of the div. How can I achieve ...