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

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

Encountering difficulty when trying to establish onclick functionality on dynamically loaded table through

Currently, I am working on a website where I am building a timeline using AJAX. I encountered an issue while trying to set the onclick event on each table row. I initially used a class selector but it did not produce any effect. After reading a post on St ...

Using jQuery to arrange information from an API into a table

Currently, I am in the process of learning jQuery as it is a new concept for me. I have attempted to make a request to an example API and received an array of objects that need to be listed in a table. However, I am facing difficulty in sorting it within t ...

Implement a select element with an onchange event that triggers an AJAX

As a newcomer to Javascript, I've been struggling to find a solution to my issue. The goal is to add an additional select option when the previous select option is changed. I attempted to implement the code below, but it's not functioning correct ...

Running npm commands from the root directory while the package.json file is located elsewhere

Although I understand that it's not ideal, I am faced with a specific directory structure that cannot be changed: [projectRootDir] [src] [tests] [otherDirs] [configuration] package.json mocha.opts other files.. ...

Unlock hidden content with a single click using jQuery's click event

I have a question that seems simple, but I can't quite get the syntax right. My issue is with a group of stacked images. When I click on an image, I want it to move to the front and display the correct description above it. Currently, clicking on the ...

Is it possible to automate a query to an API through PHP and store the results on a local drive?

Recently, I created a webpage that fetches data from an API. However, the response time from the server is quite slow, taking around 10-20 seconds to retrieve the information. To mitigate cross-domain issues, I have set up a PHP proxy for the JavaScript re ...

What is the mechanism behind image pasting in Firefox's imgur integration?

Start by launching an image editing software and make a copy of any desired image. Avoid copying directly from a web browser as I will explain the reason later on. Navigate to "http://imgur.com" using Firefox. To paste the copied image, simply press Ctrl+V ...

When utilizing the map function to render an array of objects, React encounters an error

My React application is throwing an error when using the map function. Interestingly, the code works fine in a sandbox environment. Error: ENOSPC: System limit for number of file watchers reached, watch. After creating a new React project, the error dis ...

Retrieve information from a database in real-time using Ajax without needing to set a refresh interval

Currently, I have been working on jquery/ajax requests and have managed to create an ajax request that retrieves data from a database. However, the issue at hand is that I am continuously utilizing window.setInterval() to refresh this function every x seco ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

What is the technique to enable this div to be clickable?

I am trying to make each "card" of a WordPress plugin clickable on my website. I have inserted a Pure JS element with the following code: document.getElementsByClassName('fc_card-container').onclick = function() {alert('It works!');} ...

Warning: Promise rejection not handled in error

I've been working with nodejs, express, and argon2 in my project. However, I encountered an error that has left me puzzled as to why it's happening. Strangely, even though I don't have any callbacks in my code, this error keeps popping up. H ...

Retrieve the present value from a Selectpicker using jQuery within the Codeigniter Framework

I attempted to use DOM manipulation to retrieve the value of the currently selected option from the selectpicker. My goal was to have the value of the selectpicker id="service_provider_select" printed first. However, whenever I changed the option using the ...

Having trouble with radio button validation in JS?

I'm having difficulty understanding why the radio button is not staying checked when I select another option. To demonstrate, I created a fiddle where initially the "diy" button is selected but switching to "paid" causes the radio button to jump back ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Tips for incorporating in/out animations with a container for the Slide feature:

I need help creating a component that will slide to the right when mounted, and to the left when unmounted. The Slide component should be contained in a div with the class "profile-slide-container", but I'm unsure how to achieve this. Below is the co ...

What is the method to submit post data using jQuery or JavaScript?

I need help creating a button that can send post data to another location. Is there a way I can achieve this using JavaScript, or Ajax/jQuery? If there are any details missing from my request, please let me know. ...

Does v-if cause the jquery clock picker to malfunction?

Here is my unique div where the clockpicker library functions correctly. <div class="input-group clockpicker"> <input type="text" class="form-control" value="18:00"> <span class="input-group-addon"> <span class ...