Adjusting picture dimensions with percentages in canvas and jquery

I'm currently working on a one-page project that involves a canvas where users can click to add or place images randomly. I have made progress with most of the functionality, but as a beginner in jquery and canvas, I am struggling to set a maximum size for the images. It seems challenging to make the images work seamlessly on the canvas without manually setting the canvas size in CSS. However, I am using a resizing canvas, which complicates things further.

My goal is to limit the height and width of the placed images to 80% of the viewport. I attempted to specify a maximum size in CSS, but it had no effect.

Please check out this jsfiddle

  $(document).ready(function () {
  var images = [];
    $("#siteload").fadeIn(1500);
  $('.put').each(function() {
    images.push($(this).attr('src'));
    });
    (function() {
    var
        htmlCanvas = document.getElementById('c'),
        context = htmlCanvas.getContext('2d');
        initialize();
        img = new Image();
        count = 0;
        htmlCanvas.onclick= function(evt) {
        img.src = images[count];
          var x = evt.offsetX - img.width/2,
              y = evt.offsetY - img.height/2;
          context.drawImage(img, x, y);
          count++;
          if (count == images.length) {
          count = 0;
          }
        }
      function initialize() {
        window.addEventListener('resize', resizeCanvas, false);
        resizeCanvas();
      }
      function resizeCanvas() {
        htmlCanvas.width = window.innerWidth;
        htmlCanvas.height = window.innerHeight;
      }
    })();
  });
  $(".hvr_cnt").mouseenter(function () {
      title = $("<div class='hvr_ttl'>" + $(this).children()[0].title + "</div>");
      $(this).children()[0].title = "";
      $(this).append(title);
  });
  $(document).mousemove(function(e){
     $('.hvr_ttl').css({
       top: e.pageY - $(".hvr_ttl").height()/2,
       left:  e.pageX - $(".hvr_ttl").width()/2
     });
   });
  $(".hvr_cnt").mouseleave(function (e) {
     $(this).children()[0].title = $($(this).children()[1]).html();
     $(this).children()[1].remove();
  });
body {
  margin: 0;
  padding: 0;
  background: rgb(240, 240, 240);
  width: 100%;
  height: 100%;
  border: 0;
  color: rgb(40, 40, 40);
  overflow: hidden;
  display: block;
}

.slides {
  display: none
}

#c {
  display: block;
  position: absolute;
  left: 0px;
  top: 0px;
}

.hvr_ttl {
  display: block;
  position: absolute;
  pointer-events: none;
  cursor: none;
}

.hvr_cnt {
  cursor: none;
  padding: none;
  margin: none;
}
<body ontouchstart="">
  <div class="hvr_cnt">
    <canvas id="c" title="click"></canvas>
  </div>
  <ul class="slides">
    <li><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/2000px-Smiley.svg.png" class="put" /></li>
    <li><img src="https://emojipedia-us.s3.amazonaws.com/thumbs/160/google/56/thumbs-up-sign_1f44d.png" class="put" /></li>
  </ul>
</body>

I would appreciate any assistance :)

Answer №1

Give this a shot:

htmlCanvas.onclick = function(evt) {
        img.src = images[count];

        img.width = 80 / 100 * htmlCanvas.width;
        img.height = 80 / 100 * htmlCanvas.height;

          var x = evt.offsetX - img.width / 2,
              y = evt.offsetY - img.height / 2;
          // context.drawImage(img, x, y);
     context.drawImage(img, x, y, img.width, img.height);
          count++;
          if (count == images.length) {
          count = 0;
          }


        }

Answer №2

context.drawImage(img, 0, 0,img.width,img.height,0,0,htmlCanvas.width,htmlCanvas.height);

Alternatively, you have the option to utilize background-size:cover;

Answer №3

The reason why the max-height/width property doesn't work is because everything inside the canvas operates independently from your CSS.

If you want to adjust the image size to 80%, you can use htmlCanvas.width and htmlCanvas.height to calculate the new dimensions, and then utilize

context.drawImage(img, x, y, w, h)
to set the desired image size during drawing.

You may find some useful information in this post.

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

Error messages are appearing during the installation of mediasoup

Attempting to install via Command Prompt on Windows 7 64-bit following the command npm cache --force clean ...

Disable the use of componentWillUnmount in case of an incomplete form

I have implemented a form using redux-form and I am trying to set up a scenario where if any of the form's inputs have content and the user tries to navigate away from the page, a prompt should appear. My goal is to prevent the page from being unmoun ...

Using jQuery to deactivate buttons upon submission or clicking within forms and hyperlinks

Within my Rails application, there are buttons that send data to the server. Some of these buttons are part of a form while others are standalone. I am seeking a solution to implement my jQuery code, which disables the buttons upon click, for both scenario ...

Vue JS - Issue with data reactivity not being maintained

Currently, I have implemented a pagination indicator that displays the number of results on each page. For instance, page 1 shows '1-5' and page 2 shows '6-10 out of 50 results', and so on. The logic for updating the results seems to b ...

Designating a class for the main block

Having an issue with a slider in uikit. When the slide changes, the visible elements also change their class to uk-active. I'm trying to select the central element from the active ones but css nth-child doesn't work. Any suggestions on how to do ...

Challenge with Redrawing the w2ui Grid

Using w2ui grid (1.4) with angular 1.3.4, I am attempting to display the grid in one view successfully upon first load. However, when I change the view, the grid fails to load and throws an error. ERROR: The parameter "name" is not unique. There are other ...

The <h1> element is not responding to the style attribute

Exploring HTML as a beginner has led me to an interesting issue. I've been practicing my newfound skills on W3Schools' platform and everything was running smoothly until I encountered a discrepancy in how the code is rendered on Wordpress. The s ...

Enhance User Experience with a Customized Progress Bar using Google Apps Script

I created a Google Sheets cell counter in Apps Script and need help setting up the bootstrap progress bar using the "percentage" variable. GS function cellCounter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var ...

Guide to creating a delayed response that does not block in Node and Express

I want to implement a delayed response to the browser after 500ms has elapsed. app.post('/api/login', function(req, res) { setTimeout(function() { res.json({message: "Delayed for half a second"}); }, 500); }); The code snippet a ...

Tips for ensuring that each flexbox element fills up a single line

My goal is to have each child element fill up one line by itself. See this screenshot for reference: https://i.stack.imgur.com/F40Xm.png Below is the code I am currently using: main { display: flex; justify-content: space-around; align-items: ...

Detecting when the Ctrl key is pressed while the mouse is hovering over an element in React

In my project, I have implemented a simple Grid that allows users to drag and drop items. The functionality I am trying to achieve is detecting when the mouse is positioned on the draggable icon and the user presses the Ctrl key. When this happens, I want ...

Troubleshooting connection timeouts between node.js and amqp

In my project, I am utilizing RabbitMQ through the AMQP module in Node.js with 2 producers and 2 consumers. Here is the code snippet for establishing connections for the consumers: function init_consumers( ) { console.log( 'mq: consumers connect ...

JavaScript counter that starts at 1 and increments with each rotation

I am working with an array of image IDs. let images = ['238239', '389943', '989238', ... ]; let max = images.length; The array begins at index 0 and its size may vary. For instance, if there are 5 images in the array, the i ...

Using jQuery to define color

All checkboxes are expected to have relevant information. Change the background color of the text boxes checked to #9cf. Additionally, add the string "Additional Options" before the text boxes. Note: The verification box format in these forms should be lik ...

unable to choose just one material ui checkbox

I'm new to using React and I'm currently developing a simple todo app with React JS and Material UI. To accomplish this, I've created two separate components - one for taking user input (TodoInput) and another for rendering each individual t ...

The functionality of ko.utils.arrayFilter is malfunctioning

I am attempting to sort out an array by excluding users who are already on a previous list: FullList: Tom, Tim, Jim, Jill UsersList: Tom, Jill With the help of a colleague, I managed to utilize this array filter. However, the issue is that the fil ...

What is the distinction between selecting and entering a date input value?

When a user selects a date, it needs to be immediately sent to the server. If they manually type in the date, it should be sent on blur. The issue arises when the oninput event is triggered for each keydown event, causing unnecessary server requests while ...

Adding classes to a div in a sequential animation using jQuery: A step-by-step guide

I'm aiming to create an animated effect using jQuery that replicates the motion in this GIF. I experimented with CSS3 animation keyframes, but the result was not as clean and polished as I would like. If there is a simpler way to achieve this effect u ...

Guide on how to submit x-editable input data in a Razor page

When the submit button is clicked, I would like the form to be sent using the post method. Thank you for your assistance. Here is the HTML code: <form method="post" class="form-horizontal editor-horizont ...

Firefox not recognizing height attribute in table cells

My dilemma revolves around the fact that my table cells are not displaying at the designated height. Here is the code snippet I am working with: <html> <head> </head> <body> <table style="border: 1px solid black; border-radiu ...