Create a responsive canvas with custom shapes

After designing a canvas with a gradient-filled circle, I encountered a challenge in making the canvas and the circle responsive to varying screen sizes.

Initially, I attempted to use `vh` and `vw` units for the width and height of the canvas. However, adjusting the window size resulted in the circle appearing distorted, either elongated or widened.

Question:

My goal is to proportionally decrease the size of the entire circle as the window size shrinks. How can I achieve this effect?

Code:


var c = document.getElementById('canvassun');
var ctx = c.getContext('2d');
var grd = ctx.createRadialGradient(85, 85, 20, 85, 85, 70);
grd.addColorStop(0, 'red');
grd.addColorStop(0.5, 'orange');
grd.addColorStop(0.8, 'yellow');
grd.addColorStop(1, 'white');
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(90, 90, 70, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath;
#canvassun {
  height: 30vh;
  width: 14vw;
  border: 1px solid black;
  margin: 0 auto;
  display: block;
  margin-top: 18%;
}
<canvas id="canvassun" width=170 height=170></canvas>

Answer №1

Monitor the window resize event and update the canvas accordingly

function draw() {
  var canvas = document.getElementById('canvassun');
  var context = canvas.getContext('2d');
  var gradient = context.createRadialGradient(85, 85, 20, 85, 85, 70);
  gradient.addColorStop(0, 'red');
  gradient.addColorStop(0.5, 'orange');
  gradient.addColorStop(0.8, 'yellow');
  gradient.addColorStop(1, 'white');
  context.beginPath();
  context.fillStyle = gradient;
  context.arc(90, 90, 70, 0, 2 * Math.PI);
  context.fill();
  context.closePath;
}


window.addEventListener("resize", draw);

Please Note It may be necessary to debounce the draw function for better performance

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

Is it possible to have a single listener for all events within the jQuery event namespace?

Is it possible to create a handler that can listen to ALL events within a specific namespace in jQuery using $.fn.on, off, and trigger functions? For example: $(window).on(".event_namespace", function(e){ //handler }); $(window).trigger("testEvent.e ...

Tips for evenly and fully stretching a set number of horizontal navigation items across a designated container

I want to evenly distribute 6 navigation items across a 900px container, with equal amounts of white space between each item. Here is an example: ---| 900px Container |--- ---| HOME ABOUT BASIC SERVICES SPECIALTY SERVICES OUR STAFF CONTACT ...

Switching background images with Javascript through hovering

I am currently working on implementing a background changer feature from removed after edits into my personal blog, which is only stored on my local computer and not uploaded to the internet. However, I am unsure of what JavaScript code I need to achieve t ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...

In PHP forms, ensure that only completed textboxes are submitted and empty textboxes are discarded

I've created a form that displays all available products from a database along with their prices. Users can input the quantity they want to purchase for each product, and upon submission, the total amount will be calculated. There are 5 products in th ...

Guide to executing the "brew" command on a Windows operating system

Encountering the error message "'brew' is not recognized as an internal or external command" in the Windows command prompt. https://i.sstatic.net/suFT2.png Attempting to set up the codeigniter-reactjs-example project from github, where the init ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...

Tips for entering multiple values in an input field

I am attempting to implement a feature where multiple names can be added from an autocomplete drop-down menu to an input field, similar to the example shown below: https://i.sstatic.net/D4hGA.jpg Here is what I aim to create: Upon selecting an item from ...

Does Angular 2/4 actually distinguish between cases?

I have a question about Angular and its case sensitivity. I encountered an issue with my code recently where using ngfor instead of ngFor caused it to not work properly. After fixing this, everything functioned as expected. Another discrepancy I noticed w ...

CSS not functioning properly when attempting to set overflow property to scroll

I am facing an issue with a div that has the class specified below: div.textStatement { height: 70px; overflow: hidden; } My goal is to expand the div when a user clicks on a link labeled 'Show More'. This should reveal more text and se ...

How can the onclick event be activated by pressing the enter key with inline javascript?

[FYI: I am not permitted to alter the existing markup. The div will be clicked, not a button or anchor] I have a menu that needs to comply with accessibility standards and open its submenu upon being clicked. This onclick function needs to be triggered w ...

What is the best way to revert the Highcharts bar color back to its default color?

I am currently working with Highcharts version 4.1.10 In my bar chart, I have implemented a feature where the color of the bar changes when its value exceeds a certain threshold. //This function is called at regular intervals by a timeout function myTime ...

Please input new items by clicking a button

I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over ...

Oops! We encountered an issue trying to find the "list" view in the views directory

Here are the images I have: This is the code for my app.js file And this is the code for list.ejs located in the views directory Unfortunately, my index.html file is empty. Below is the full error log: Error: Failed to lookup view "list" in the views di ...

Breaking Down Particular Phrases

I am currently developing an application that necessitates the user to select a location, which will then guide them to the designated spot using Google Maps. The locations are stored as an array of JSON files. Below is an example of what the list looks li ...

Exploring the intricacies of parsing nested JSON data

Could someone assist me with understanding the following json data? { "Message":"The request is invalid.", "ModelState":{ "model.ConfirmPassword":["The password and confirmation password do not match.","The password and confirmation passwo ...

How to capture text outside of a HTML tag using Selenium with Python?

I need help extracting the specific text inside a div element that is not enclosed by a label. <div style="color:red;"> <label> Total Amount Due:</label> $0.00 </div> Only interested in retrieving the $0.00 amount from th ...

Submitting content to numerous webpages

I'm looking to submit form data on multiple pages, while keeping the main action as "". After clicking, I want the page to refresh but also send the POST data to another .php file. This is necessary because the other .php file generates a graph that ...

Jquery menu block shift

I am looking to implement a timer for the submenu within my menu. The idea is to show the submenu for 3 seconds after a mouse-over event. I have already set up a function to display and hide the submenu, but I am facing an issue where the submenu shifts to ...

Issue with displaying record attribute as a text variable

I'm currently attempting to retrieve the attribute odata.type from a record so that I can adjust my EditForm based on its value. Strangely, when I utilize a constant to achieve this and print it with console.log, it appears as follows: ƒ HWType(_ref ...