Tips for spinning HTML5 Canvas's background image and adjusting the zoom with a slider

As someone who is new to the world of coding, I have a few goals in mind:

  1. First and foremost, I want to create a canvas.
  2. I also aim to add a background image to the canvas. Importantly, this background image should be separate from any foreground images created using 'drawImage(image, x, y)'.
  3. One of my key objectives is to include a slider that allows users to zoom in and out on the background image. However, I am facing a challenge in resizing the image since it's positioned in the background.
  4. Additionally, I hope to incorporate two buttons - one for rotating the image left, and the other for rotating it right.

All these tasks must be accomplished using HTML5, CSS3, and jQuery only.

I would greatly appreciate it if someone could explain these concepts in a beginner-friendly manner, preferably with detailed explanations of the code.

Thank you in advance!

Below is the code snippet that I've experimented with:

<div class="slider" style="width:500px; height:10px;"></div>
<br />

<div id="div_buttons">
    <table border="0">
        <tr>
            <td>
                <input type="button" id="rotateLeft" align = "left" value="Rotate Left" />
            </td>

            <td>
                <input type="button" id="rotateRight" align = "left" value="Rotate Right" />
            </td>
        </tr>
    </table>
</div>

<!--HERE IS THE STYLE TAG... -->
<style type="text/css">
    img
    {
        opacity: 0.5;
    }

    .canvas
    {
        background: url('script.jpg');
        opacity: 0.5;
    }
</style>

<!--HERE IS THE JAVASCRIPT INSIDE <SCRIPT> TAG... -->
<script type="text/javascript">
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext('2d');
    var globalElement_width;
    var globalElement_height;

    $(document).ready
    (function() {
        $img = $('.canvas img');
            globalElement_width = $img.width();
            globalElement_height = $img.height();

            $(".slider").slider
        ({
                    step: 1,
                    min: 10,
                    max: 100,
                    value: 0,
                    slide: function(event, ui)
                        {
                            resize_img(ui.value);
                        }
            });

            $("#rotateLeft").click(function() { 
                $('canvas').css({
                            "transform":"rotate(-90deg)"
                            });
                }
            ) //addClass("left")

            $("#rotateRight").click(function() {

                $('canvas').css({
                            "transform":"rotate(0deg)"
                            });
                }
            )
        });

        function resize_img(val) 
    {
        var width = globalElement_width;
        var height = globalElement_height;
        var zoom_percen = (height * 1); // Maximum zoom 50%
        var ASPECT = 10;//zoom_percen / 30;
        var zoom_value = val / 1;
        var size = width + ASPECT * zoom_value;
        var d = ASPECT*zoom_value/10;          

        $img = $('.canvas img');
        $img.stop(true).animate({
        marginTop: -d,
        marginLeft: -d,
        width: size,
        height: size
        }, 250);
    }

</script>


</body>

Answer №1

After struggling with a few issues, I finally found the answer to my own question. The code seems to be working smoothly, except for some trouble with image rotation and zooming.

Here is the solution I came up with:


        <div id="div_buttons" style="position: absolute; top: 580px;">
            <table border="0">
                <tr>
                    <td>
                        <input type="button" id="rotateLeft" align = "left" value="Rotate Left" />
                    </td>

                    <td>
                        <input type="button" id="rotateRight" align = "left" value="Rotate Right" />
                    </td>
                </tr>
            </table>
        </div>

        <div id="result" style="position: absolute; top: 520px;" >This is where the div is located</div>

    <!--HERE IS THE STYLE TAG... -->
    <style type="text/css">
        img
        {
            opacity: 0.5;
        }

        .canvas
        {
            background: url('sky.jpg') no-repeat 30% 30%;
            height: 500px;
            width: 500px;
            repeat: false;
            opacity: 0.5;
            repeat: none;
        }
    </style>

    <!--HERE IS THE JAVASCRIPT INSIDE <SCRIPT> TAG... -->
    <script type="text/javascript">
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext('2d');
        var globalElement_width;
        var globalElement_height;
        var newangle = 0;
        var operation = "";

        $(document).ready
        (function() {
            $img = $('.canvas');
                globalElement_width = $img.width();
                globalElement_height = $img.height();

                $(".slider").slider
            ({
                        step: 1,
                        min: 1,
                        max: 100,
                        value: 0,
                        slide: function(event, ui)
                            {
                                resize_img(ui.value);
                            }
                });



                //THIS IS THE CODE THAT MAKES CANVAS BACKGROUND ROTATE LEFT.
                $("#rotateLeft").click(function() { 
                    $('.canvas').css({
                        "transform":"rotate(-90deg)"
                                });
                    }
                ) //addClass("left")

                //THIS IS THE CODE THAT MAKES CANVAS BACKGROUND ROTATE RIGHT.
                $("#rotateRight").click(function() {
                    $('.canvas').css({
                            "transform":"rotate(0deg)"
                                });
                    }
                )



                //TRYING TO MAKE CANVAS ANNOTABLE.

                //ALL MOUSE LISTENERS ARE SET HERE.
                canvas.onmousedown = function (e) //WHEN MOUSE IS CLICKED
                {
                    canvas.isDrawing = true;

                }

                canvas.onmouseup = function (e) //WHEN MOUSE CLICK IS RELEASED
                {
                    canvas.isDrawing = false;

                }

                canvas.onmousemove = function(e)
                {

                    var res = document.getElementById('result');
                    res.innerHTML = e.pageX + ", " + e.pageY;

                    if (!canvas.isDrawing) {
                       return;
                    }

                    var x = e.pageX - this.offsetLeft;
                    var y = e.pageY - this.offsetTop;
                    var radius = 5; // or whatever
                    var fillColor = '#ff0000';
                    context.fillCircle(x, y, radius, fillColor);
                }

                context.fillCircle = function (x, y, radius, fillColor)
                {
                    //alert("fillCircle is here...");
                    this.fillStyle = fillColor;
                    this.beginPath();
                    this.moveTo(x, y);
                    this.arc(x, y, radius, 0, Math.PI * 2, false);
                    this.fill();
                }
            });

            function resize_img(val) 
        {
            context.save();
            var width = globalElement_width;
            var height = globalElement_height;
            var zoom_percen = (height * 1); // Maximum zoom 50%
            var ASPECT = 10;//zoom_percen / 30;
            var zoom_value = val / .5;
            var size = width + ASPECT * zoom_value;
            var d = ASPECT*zoom_value/10;          

            $img = $('.canvas');
            $img.stop(true).animate({
            marginTop: -d,
            marginLeft: -d,
            width: size,
            height: size
            }, 250);
            context.restore();

        }
    </script>


</body>

Answer №2

You have the option to set a background image using this method. If you are interested in implementing zoom in and zoom out functionality for an image, you can refer to this Stack Overflow discussion.

It might provide some assistance.

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

What impact does the text-shadow property have on altering the color of hsla text?

I created a header that changes color to be slightly transparent with a black outline when hovered over (achieved using 4 text-shadows). However, I encountered an issue when trying to use hsla() to define the color. The color defaults to black with 100% o ...

Captivating Images accompanied by Descriptive Captions

I was wondering if there is a straightforward method using only CSS and HTML to address this particular issue. I am in the process of creating a marquee that displays images within a fixed-width div. The number of images exceeds the capacity of the div, ...

javascript Arabic speech synthesis

Attempting to utilize SpeechSynthesisUtterance for Arabic language Successfully functioning with English content $(document).ready(function() { var u1 = new SpeechSynthesisUtterance('Hello world!'); u1.lang = 'en-US'; u1.pitch ...

Is it possible to halt the execution of a code or skip the remainder of it if a specific condition is met using jQuery?

Is it possible to prevent a code from completing or skipping the remaining parts based on a specific condition? For example, var stopCode = false; if (stopCode === true) break; .... .... blah blah blah the remaining part of the code .... ... Can this b ...

Floating above a divided rectangle div

Imagine a rectangular div divided into two parts, each part forming an L shape (as illustrated below), with region 1 representing the left-side L and region 2 representing the right-side L. I am interested in changing the background color of region 1 on h ...

How to center a text box within a div using CSS

Looking for equal margins on top and bottom? Here's how to achieve it: If you have a container div like this: <div id="search"> <input id="txtSearch" type="txt"> </div> Your CSS should look something like this: #search{ m ...

Exploring the interplay between jQuery functions and the "Class" method in Javascript

Is there a way to reference a parent "class" method in Javascript from a jQuery function? Here's an example scenario: $Object.prototype.TestFunction = function(arg){ alert(arg); } $Object.prototype.foo = function(){ $(something).click(function ...

Modifying the color scheme of the table background and text

After finding a code example online to assist with creating a table in my project, I am faced with the challenge of changing the background color of the white rows to match the dark blue used for others. Additionally, I cannot figure out how to change the ...

CSS trick for stylish arrow placement on top of a slide

Hey there! This is my first time navigating through the slick carousel functionality. I'm currently facing a challenge with adjusting the positioning of the arrow within the slider. My goal is to have the arrow displayed at the top level just like the ...

What are some ways to incorporate JQuery with getElementById?

i am trying to retrieve all input elements within a form using JavaScript formEditable = document.getElementById("formid").getElementsByTagName("input"); However, I would like to achieve the same result using jQuery instead formEditable = $("#formid").f ...

Transforming PHP Variable Using Ajax

I have a variable called $type and I need it to be either month or year. This change should occur when a div is clicked. I attempted to use an onclick event with an ajax call. The ajax call and the variable are both in the same script (index.php). Within ...

What is the reason this :class="{}" is not functioning properly in Vue.js?

I have created a simple file that contains a reactive Array of objects where each object has a property called "checked" which is a boolean that toggles based on a checkbox. I am using a v-for directive to iterate through the array of employees and render ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

Enhance your website with a multi-column Pure CSS drop-down menu

Can anyone help me with this issue I'm facing? I am struggling to add a second column to the main "Authorized Brands" menu, and when I tried to break it up, it affected the rest of the columns due to the width being set at 1000px. This is the code I ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Is it possible for me to alter the script for my button's onclick

Is there a way to replicate all properties of a div when creating a clone using JavaScript code? I have an existing script that successfully creates a clone of a div when a button is pressed, but it does not copy the CSS properties. How can I ensure that t ...

jQuery checkbox toggles multiple divs instead of targeting specific ones

I have set up my page to display divs containing posts using a specific format. The divs are structured as follows (replacing # with the postID from my database): <div id="post_#> <div id="post_#_inside"> <div id="like_#"> ...

Retrieving the chosen date from a calendar using a jQuery function

Hey there, I need help with showing tasks created on a specific date by selecting that date from a full month calendar. There are multiple tasks created on the selected date, and I want to trigger a jQuery event to fetch data for that date. However, my i ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...