Tips for adding your artistic touch to photos

I'm currently facing a challenge in creating a chart that overlaps an image. The bars and text on the chart are displaying perfectly when I remove the background image. However, I'm struggling to get the bars and text to appear on top of the image. Any assistance on resolving this issue would be highly appreciated. Thank you.

js:

    (function(){
        var canvas = document.createElement('canvas');

        canvas.width = 400;
        canvas.height = 300;

        document.body.appendChild(canvas);

       var ctx = canvas.getContext('2d');

        var img = new Image();

        img.src = 'images/bg.jpg';

        img.addEventListener('load', function(){
                ctx.drawImage(img, 0, 0, 400, 300);
            },
            false);




        var charData = [Math.floor(Math.random()* 100), Math.floor(Math.random()* 100), Math.floor(Math.random()* 100), Math.floor(Math.random()* 100)];

        //console.log(charData);

        var maxBarHeight = 200;




        var drawBars = function(){
            ctx.font = '14px Georgia';

            for(i=0; i<charData.length; i++){
                ctx.beginPath();
                ctx.fillStyle ='rgba(100, 200, 200, 0.75)';
                var height = maxBarHeight*charData[i]/100;
                ctx.height = height;
                ctx.rect(i*80+90,270-height,50,height);
                ctx.fill();
                ctx.font.fillStyle ='rgb(255,255,255)';
                ctx.fillText(charData[0], 100,50);
                ctx.fillText(charData[1], 180,50);
                ctx.fillText(charData[2], 265,50);
                ctx.fillText(charData[3], 350,50);
            }



        };

        var drawCharText = function(){
            console.log("in draw text");
            ctx.font = '20px Georgia';
            ctx.fillStyle = 'rgb(0,0,255)';
            ctx.fillText('TEST GRADS', 30,30);

        };




        drawBars();
        drawCharText();

    })();

html:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Goal9: Assignment: Canvas</title>
    </head>
    <body>
    <script src="js/main.js"></script>
    </body>
    </html>

Answer №1

To prevent the image from overlapping with the bars and text, delay drawing the image until after it has finished loading asynchronously. Ensure that the call to draw the bars and text is within the load event of the image for a seamless display.

Answer №2

If you're considering stepping away from using JavaScript for this specific task, PHP and the GD Library could be a viable alternative. By utilizing PHP and creating a cronjob to refresh images by cycling through them, you can achieve your desired outcome.

For more information, visit: http://www.php.net/manual/en/book.image.php

I have personal experience with the GD library while working on a server listing website. It allowed me to generate custom banners for each server that displayed important information like the number of online players, uptime, and other statistics.

You can find helpful examples on the official PHP website linked above. While this response may not provide an immediate solution, I hope it offers valuable insight. Best of luck!

Answer №3

It appears that your image is currently taking some time to load, causing it to load last instead of first. To resolve this issue, I recommend wrapping your other two draw functions within your event listener.

        img.addEventListener('load', function(){
            ctx.drawImage(img, 0, 0, 400, 300);
            drawBars();
            drawCharText();
        },
        false);

http://jsfiddle.net/GdtUD/

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

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

Identifying the class name of SVGAnimatedString

While working on creating an SVG map, I encountered an issue where the functions triggered by hovering over 'g' elements were not functioning as expected. In order to troubleshoot this problem, I decided to check for any issues with the class nam ...

Utilize AJAX to dynamically insert data into the database

I have created a JSP page that displays records, and now I am looking to include a dynamic link or button in the JSP that allows inserting data into the database without needing to refresh the page. This link should open a pop-up window with input fields ...

What techniques can you leverage in React to iterate through nested arrays, such as using .map or other alternatives?

As part of my work, I often come across an Array structure similar to the one below: Array = [ { product1, orderedBy = [{customer1}, {customer2},.....,{customerN}] }, { product2, ...

Session management functions properly in Postman, however, encountering issues when attempting to use it on a web

Working on a NodeJS project using express-session to handle sessions. When sending a post request to http://localhost:5500/login, a session is created with an additional property userid. Upon making a get request to http://localhost:5500/ using Postman, th ...

Identify the transition of the parent element containing the <iframe> from a hidden state to a

Is there a way to identify when an iframe is shown after being hidden? HTML : <div style="display:none"> <iframe></iframe> </div> When the <div> is displayed using jQuery with $('div').show();, how can I determi ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

Running the `npm build` command does not automatically execute the "build" script specified in the package.json file

I am exploring a new approach for my module by utilizing npm build instead of relying on gulp / Grunt or other specialized build tools. "scripts": { "build": "node build.js" }, The content of my build.js file is simply: console.log('Hello') ...

Disabling Scrolling in AngularJS Material Tab Components

I'm experimenting with AngularJS Material components and struggling with creating tabs. Every time I add a tab, the content inside the child md-content element automatically gets a fixed height with a vertical scrollbar instead of adjusting its heigh ...

Tips for including descriptions on individual images within the jQuery PhotoStack gallery

Recently, I encountered a challenge. I am currently utilizing a PHP file for accessing images stored in a specific folder. Here is the snippet of my PHP code: <?php $location = 'albums'; $album_name = $_GET['album_name']; $files ...

Proceed to the section with modal

My goal is to create a modal with 4 sections, each loading its content dynamically using the .load() function to the container on the right side. The challenge I'm facing is that I have a footer menu that triggers the modal to open, and I need it to ...

Retrieving JSON data with Node.js

Receiving a JSON response from TMDB: { "id": 283350, "results": [ { "iso_3166_1": "BR", "release_dates": [ { "certification": "12", "iso_639_1": "pt", "note": "Streaming", "release_date": ...

The art of connecting Javascript commands in succession

I'm struggling to grasp the concept of chaining and return in JavaScript. For example, consider the following code snippet: let array = [1, 2, 3] let newArray = array.map(val => val * 10).map(val => val * 10) console.log(newArray) // [100, 200, ...

Pagination in DynamoDB: Moving forward and backward through your data

Currently, I am utilizing DynamoDB in combination with NodeJS to display a list of objects on the user interface. Given that DynamoDB can only process 1MB of data at a time, I have opted to implement pagination. This allows users to navigate between pages ...

Is it possible to deactivate an element based on a specific string present in the URL?

<div class="custom-class1"> <div class="custom-class2" id="custom-id1">hello 1</div> <div class="custom-class3" id="custom-id2">hello 2</div> <div class="custom-class4" id="custom-id3">hello 3&l ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

Using a combination of Javascript and PHP to dynamically update the innerHTML of multiple elements

I am working on updating the innerHTML of a webpage using Javascript after an onclick event. In my java.js file, I am utilizing this code to access a PHP page that echoes back the text for updating the innerHTML. The issue arises when attempting to update ...