What is the function of object-fit when used with the canvas element?

Despite my thorough search, I have not come across any documentation to clarify this issue.

Is it possible to use object-fit cover on canvas elements? My experiments have yielded unexpected results so far.

Could someone provide me with a conclusive answer?

Answer №1

object-fit1 will only take effect when there is a change in aspect ratio (a distortion) and applies solely to replaced elements (canvas being a replaced element)

Here's a simple example:

var canvas = document.querySelectorAll("canvas");
for (var i = 0; i < canvas.length; i++) {
  ctx = canvas[i].getContext("2d");
  ctx.fillRect(50, 50, 100, 100);
}
canvas {
  width: 100px;
  height: 250px;
  border: 1px solid red;
  display: block;
}

.box {
  display: inline-block;
  border: 2px solid green
}
<div class="box">
  <canvas width="200" height="200"></canvas>
</div>
<div class="box">
  <canvas width="200" height="200" style="object-fit:contain;"></canvas>
</div>
<div class="box">
  <canvas width="200" height="200" style="object-fit:cover;"></canvas>
</div>

As shown, I set the canvas dimensions to 200x200 (1:1 ratio), then altered it using CSS, breaking the ratio (no longer a square) where object-fit comes into play to correct this.

A relevant question to grasp the distinction between setting width/height via attribute and with CSS: Why box-sizing is not working with width/height attribute on canvas element?


1According to the specification, all values (except the default fill) strive to maintain the aspect ratio:

contain

The replaced content is sized to maintain its aspect ratio while fitting within the element’s content box: its concrete object size is resolved as a contain constraint against the element’s used width and height.

cover

The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box: its concrete object size is resolved as a cover constraint against the element’s used width and height.

none

The replaced content is not resized to fit inside the element’s content box: determine the object’s concrete object size using the default sizing algorithm with no specified size, and a default object size equal to the replaced element’s used width and height.

The none value is a bit tricky but essentially means maintaining the intrinsic default image size without scaling like contain or cover

var canvas = document.querySelectorAll("canvas");
for (var i = 0; i < canvas.length; i++) {
  ctx = canvas[i].getContext("2d");
  ctx.fillRect(50, 50, 100, 100);
}
.box canvas {
  border: 1px solid red;
  display: block;
  object-fit:none;
}

.box {
  display: inline-block;
  border: 2px solid green
}
<canvas width="200" height="200"></canvas>
<div class="box">
  <canvas width="200" height="200" style="width:100px;height:200px;"></canvas>
</div>
<div class="box">
  <canvas width="200" height="200" style="height:50px;width:200px;"></canvas>
</div>

Related: CSS object-fit: contain; is keeping original image width in layout

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

Deactivate numerous buttons with the help of jQuery

Within my MVC view, I have a Razor foreach loop that generates table rows with buttons: @foreach (var item in Model) { <tr> <td>@item.Id</td> <td> <button id="btn" class="button btn-primary" type= ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Conceal the sidebar menu by clicking anywhere outside of the menu bar or the designated button

I attempted to create a menu similar to the semantic UI, but so far I have only been able to click the menu button to open and close the menu. I am using a toggle class to display the sidebar, but I'm unsure if this approach is entirely correct: < ...

What is the best way to incorporate a gratitude note into a Modal Form while ensuring it is responsive?

Currently, I have successfully created a pop-up form, but there are two issues that need fixing. The form is not responsive. After filling/submission, the form redirects to a separate landing page for another fill out. Expected Outcome: Ideally, I would ...

image in responsive css design

Image 1 (Current Layout) Image 2 (Desired Layout) I am trying to achieve a responsive layout similar to the second image. However, I seem to be stuck with the layout from the first image. Here is the CSS code I'm currently using: @media (max-width ...

Modifying the Vue page background directly from a page: a step-by-step guide

UPDATE: I recently discovered that I need to modify the body background-color, but I am unsure of how to accomplish this from within the style of this page based on the wrapper's class. The class is determined by the data values. I aim to change the ...

Looking for help combining HTML5 Canvas and JavaScript to showcase images. Can anyone lend a hand?

I am currently in the process of developing an Android game using HTML5 and Javascript. I have managed to make some progress, but I have encountered a problem that has left me puzzled. Initially, my JS file and Html file were functioning well together for ...

Identify modifications in the content within an iframe, where the content is constantly changing due to the use of

Alright, so I have a jQuery mobile enabled page that is being loaded inside an iFrame. Typically, if I want to detect changes in the content of an iFrame, I would use: $('iframe').load(function(){ //content changed! }); However, in this par ...

What is the reason for being unable to submit the value of an input that is disabled?

When I try to save the value of an input field that is disabled and has the required attribute, I receive an error message stating that "field_name is required". Why am I unable to insert a value when the input field is disabled? <input disabled type=&q ...

The nested div does not have scrolling functionality

I'm currently working on making a nested div scrollable, but I'm encountering some challenges. The problematic div in question is the one with the "items" class. <body> <div class="page-wrapper"> <div class="header">Heade ...

Excessive width of Bootstrap container

Encountering a rather simple issue: the bootstrap container inside my navbar is too wide, causing an unwanted horizontal scrollbar as it expands the body. You can view the problematic page here. The theme used for this site can be found here. What's ...

Enable users to modify the URL in the window.open() function

In the code snippet below, a new window opens when a user clicks on a button: $('.loginButton').click(function () { var strString = $("#medlineSearch").val() var strSearch = "http://google.com&query="; var url = strSearch + strSt ...

The action does not execute when the form is submitted

I’m currently working on a simple registration form, but I’ve encountered an issue with my code. Despite troubleshooting, I can’t seem to identify any errors in my code. Upon submission of the form, the page fails to redirect to register.php. Below ...

dismiss data and button for closing notification bar

I am currently using a notification bar at the top of my website, instead of a modal. I am wondering if it is possible to click the X (close-button) and have the notification bar disappear. I attempted to use data-dismiss but it did not work. Also, how can ...

Two elements failing to display side by side

Can someone help me figure out how to align the quantity and Add-to-cart button on the same line? The quantity is displaying as a block element even though I set it as inline... any suggestions would be appreciated! Visit this link for reference. I' ...

Creating an invoice or money receipt using HTML is a straightforward process that involves using specific code and

Currently, I'm in the process of developing an application for a land developer company. The administrator of this application will be responsible for creating invoices, money receipts, and bills. I am looking to design these documents to resemble th ...

Switch up the background hue of a multi-level dropdown menu in Bootstrap 5

Has anyone attempted to modify the background color in a multi-dropdown menu using Bootstrap 5? You can find the original code here. I am looking to change the background color for visited/active items in a multi-level dropdown menu. The code snippet belo ...

increasing the SQL integer value with padding

Is it possible to apply padding to certain INT return values retrieved from an SQL database using CSS within a div tag? I need specific numbers to have padding-left: 20px; while other specific numbers should have padding-right: 20px;. This presents a styl ...

Styling HTML elements using CSS within PHP echo statements

I am a beginner when it comes to PHP and I'm trying to figure out how to style this table. I tried creating a class, but changing the styles in a separate CSS file didn't work for me. Should I use style tags? How should I go about styling this? ...

Prevent users from selecting elements on the mobile site

Hey there! I'm currently working on preventing users from selecting items on my mobile site. While I've been successful in doing so on a regular website using the CSS class below .unselectable { -moz-user-select: -moz-none; -khtml-user-s ...