Tips on adjusting the size of an HTML canvas specifically for the display

Currently, I am working on an innovative project utilizing HTML5 and canvas:

The challenge at hand is to draw on a canvas with dimensions of 2200px/1600px (width/height), display it on my website in a smaller window sized at 600px/400px. However, post client modifications, the canvas must be converted into an image with its original width and height of 2200px/1600px.

<canvas id="iBack" style="width:<?= $backgroundWidth ?>px; height:<?= $backgroundHeight ?>px; z-index: 0; border: 1px dotted red;"></canvas>

Answer №1

To prevent distortion, consider using CSS for proportional scaling.

var scale=2200/600;
canvas.style.width*=scale;
canvas.style.height*=scale;

However, be cautious as this may result in a pixelated image and text after scaling.

If the pixelation is too severe, you can recreate the original image with scaled text.

Check out the provided code and Demo: http://jsfiddle.net/m1erickson/dZ4D6/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var scale=1.0;
    var fontsize=36;
    var fontface="verdana";
    var fullImageWidth,fullImageHeight;

    var img=new Image();
    img.onload=function(){
       redraw(img,"Hello",20,35,1.25); 
    }
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";

    function redraw(img,text,textX,textY,scale){

        canvas.width=img.width*scale;
        canvas.height=img.height*scale;

        // draw the scaled image
        ctx.drawImage(img,0,0,img.width,img.height,0,0,img.width*scale,img.height*scale);

        ctx.font=(fontsize*scale)+"px "+fontface;

        // draw the scaled text
        ctx.fillText(text,textX*scale,textY*scale);

    }

    $("#redraw").click(function(){
        if(scale==1.00){
            scale=0.50;
        }else{
            scale=1.00;
        }
        redraw(img,"Hello",20,35,scale); 
    });

}); // end $(function(){});
</script>

</head>

<body>
    <button id="redraw">Redraw</button><br>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

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 there a way to retrieve the headers from an HTTP response in JavaScript that wasn't initiated by an AJAX request?

I have a login page setup to send an HTTP post request to the server, which then redirects me to another page on the server in the response message. On this new page, I need to access the location header to obtain a specific value for future server tasks. ...

The utilization of Display Flex resulting in the enlargement of the containing div

I am currently learning CSS and trying out some new things. I am looking to create a page with two side-by-side divs: one for the sidebar and the other for the main content. My goal is to have the sidebar take up 400px of width and allow the content part t ...

Adding a prefix to the imported CSS file

My React app, created with create-react-app, is designed to be integrated as a "widget" within other websites rather than functioning as a standalone application. To achieve this, I provide website owners with minified JS and CSS files that they can inser ...

What is the best way to implement an undo-list using arrays?

My current project involves creating a paint program in JavaScript, and I am aiming to implement an undo function rather than just an eraser. How can I store events in an array and then enable the deletion of each event individually? I have a dropdown men ...

Perfectly aligning the Update Progress Animation in real-time

I am currently utilizing the Ajax UpdateProgress with a loading gif attached. The issue I am facing is how to ensure that the loading.gif always appears in the center of the screen, even if the user is at the very top or bottom of the page. Is there a meth ...

Troubleshooting code: JavaScript not functioning properly with CSS

I am attempting to create a vertical header using JavaScript, CSS, and HTML. However, I am facing an issue with the header height not dynamically adjusting. I believe there might be an error in how I am calling JSS. Code : <style> table, tr, td, t ...

Sending data from an HTML textarea to a PHP variable without user input

After spending more than two days searching for a solution to this problem, I am now reaching out directly with my question. Although there have been some hints and partial answers, nothing has definitively resolved the issue I am facing, prompting me to m ...

Enhance your interface with stunning JQuery code snippets

We are in the process of developing a web application that will be fully 2.0 compliant (utilizing AJAX and more). Although I am primarily a rich-client and server-side developer, my knowledge of Javascript is limited to a functional level. However, based ...

Please provide the text input for the specified version numbers (1.1, 1.2, 3.0, etc.)

I'm currently working on a form that includes a section for searching by version number: <label class="formLabel">Version</label> <html:text property="valueVersion" styleClass="value" tabindex="11"/> <br/& ...

Eliminate any unnecessary gaps that may exist between the cards within the deck

Utilizing Jinja2 with Flask to render a list on an HTML page, I aim to produce card decks containing data from the list using a Jinja2 loop. This is my current HTML code: <div class="container-fluid"> <div class="row"> <div clas ...

Divide and Insert a Gap in Phone Number

I need help formatting a telephone number so that there is a space between every third and seventh character. var phoneNum = "02076861111" var formattedNum = [phoneNum.slice(0, 3), phoneNum.slice(3,6), " ", phoneNum.slice(6)].join(''); console ...

Tips for Eliminating Unnecessary Space Above the Navigation Bar

I have a problem with the top navbar on my test site. There is some extra space above it that I want to remove so that the navigation extends all the way up to cover the viewport. Here is an image of what I'm trying to achieve: https://i.stack.imgur.c ...

Aligning characters according to Unicode standards

I'm looking to showcase a Unicode character at the center of a button. Below is the code snippet: <div class="col-xs-1"> <button class="btn btn-tool"> <span></span> </button> </div> span:before { ...

Is there a way to condense a paragraph of text without using a span or div element?

There is a common scenario where I often encounter this issue: <span> <p>hello world</p> </span> It involves reducing the width of a paragraph to fit the text, but unfortunately it leads to clutter in my HTML. Is there a way to ...

Aligning a child element in the center along the horizontal axis within a parent container that is smaller in width than

I have been attempting to center an <img> element horizontally within a <div> that is narrower than the image itself. The <div> has overflow: hidden applied to it. For example, if the image is 500px wide and the DIV is 250px wide, is the ...

Retrieving JSON information stored in a JavaScript variable

I'm feeling a bit embarrassed to admit it, but I am still learning the ropes when it comes to Javascript development. I've hit a roadblock and could really use some help from the experts here. Thank you in advance for all the assistance this comm ...

``In Internet Explorer, the function to swap the image source when hovering over the parent element

I'm trying to make it so that when I hover over the parent (Li) tag with my mouse, the src attribute of the child img tag changes. This code works correctly in Chrome but not in Firefox and Internet Explorer. <li class="player"> . . //some c ...

Is the tabindex feature malfunctioning for the submit button in an HTML form?

Hey there, I created the design like this. However, the submit Tabindex is not working as expected. Can you please take a look at it and let me know what might be causing this issue? <input id="id" type="text" value="" class="input" tabindex="1"/> ...

Generate a distinct identifier for each new div created, and then use jQuery to access it

I am just starting to learn php and am a beginner in jQuery. On my php page, I have data pulled from a mySQL table. My goal is to assign unique ids to the h3 containing "View Job" and the div that displays the job description. I want to then use jQuery to ...

What is the reason behind my POST ajax request being sent as a GET method?

After days of relentless searching, I am finally seeking help for an issue that has been driving me crazy. I attempted to submit a form using an AJAX call with a POST method. However, the $(form).submit() function did not work as expected in my situation. ...