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

CSS: Achieving vertical centering without specifying a fixed height using line-height. Is it possible?

Using line-height to vertically center text within an inline-element is a technique I often employ. Here's a demo I created: body, section { width: 100%; } section { background-color: lightGrey; } #wrap { margin: 30px auto; width: 100%; ...

Utilize AJAX and C# to seamlessly map JSON data onto an object

What is the best way to utilize JSON formatted data received from an AJAX request in C#? Check out this View with JQuery and AJAX: <script type="text/javascript"> $(function () { $("#btnGet").click(function () { var values = ...

Jquery code that mimics pressing a key downwards is not functioning properly to execute a keyboard shortcut

I would like to express my gratitude in advance for any time and effort dedicated to this matter. So, here's the situation: I have a script that is meant to simulate a key press event after 3 seconds once the page is loaded. The goal was to trigger a ...

Achieve uniform display across browsers: Implement Chrome's overflow ellipsis feature on Firefox

I am seeking a CSS solution to achieve the same "overflow: hidden" and "text-overflow: ellipsis" behavior in Firefox as I get in Chrome. In Chrome, when the width of the tag is reduced, the text gets hidden and replaced with an ellipsis. However, in Firefo ...

What is the best way to center this image horizontally within its variable-sized parent container?

I am currently working on a webpage that has a responsive design. The page features a list of products, with the product listing adjusting in size as the page width changes. My goal is to center the product image within its container, ensuring that the i ...

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

Is it possible that an object sent as a response body from a Spring MVC application's controller cannot be fetched using the jQuery AJAX method?

After making an AJAX call, the EmployeeBean object is not being returned and no exception is being thrown. Here is the code snippet from the controller method: I am trying to return an EmployeeBean object from this method using @Responsebody @RequestMapp ...

Require help with personalizing a jQuery horizontal menu

I recently downloaded this amazing menu for my first website project By clicking the download source link, you can access the code Now, I need your kind help with two issues: Issue 1: The menu seems to be getting hidden under other elements on the page ...

In Internet Explorer 8, the Radmenu hover menu may appear below surrounding Radmenus

Utilizing a radmenu, I am able to dynamically generate a submenu structure by examining folders in sharepoint document libraries. However, when placing multiple controls on the page, the root menu from other controls overlaps with the submenu of the curren ...

It is not possible to simultaneously utilize the properties `display: inline-block` and `width: 100%`

As someone with limited CSS knowledge, I have encountered a challenge. My goal is to ensure that my website's body has a width of 100%, while also preventing the content from wrapping when the browser window is resized. To achieve this, I attempted a ...

Adding JQuery Event Handlers to Dynamically Generated Controls

When adding content to my existing div on the page, I encounter an issue where events do not work properly after appending. The text being added contains HTML code within a string. It seems that jQuery only loads controls once on page load, so I may need ...

The "src" attribute is missing from the image on the left side

I'm currently facing an issue with the src attribute in this code: An event updates the src based on a variable retrieved from a form. The image files cannot be renamed, so I must work with their existing names. The problem arises as all file names c ...

Issues with a top navigation bar

I'm currently working on customizing a header menu to my liking but have limited experience with CSS. The header menu consists of two main items, each with a dropdown. I envision the first menu item to look like this upon hover: And for the second m ...

Retrieve all div elements by their data attribute until reaching a certain condition

I am working on an innovative jquery accordion menu using divs instead of the typical li tags. Each div contains a unique data attribute (data-level) with values ranging from 1 to 4, and so on... To achieve the desired functionality, my "toggle" function ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...

CSS text width going from left to right

I am attempting to create a text fade effect from left to right, inspired by the technique discussed in this answer. However, I would like the text to be concealed behind a transparent background div instead of the white background used in the example. I ...

Customizing Each Menu Item in WordPress

I am currently working on customizing my WordPress Menu. My goal is to assign a unique color to each menu item, while ensuring that the background color of child elements within pages and posts matches the parent text color. Specifically, I envision the f ...

Placing a table within a div causes the div to expand in width beyond 100%

A situation has arisen where a table with a large number of columns (30 columns) is being affected by the white-space:nowrap style set on each th tag, causing the parent div to stretch unnaturally. How can this issue be resolved and allow for a horizonta ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...