简体   繁体   中英

Canvas resize with image in it

I'm trying to get image resized from mm to pixels after clicking submit button but all I can achieve is cropping original image. It looks like canvas is not refreshing image after changing size. How can I do it properly?

Example on jsfiddle

JS Code:

document.addEventListener("DOMContentLoaded", function() {
    var width = 0;
    var height = 0;
    var colors = 0;
    var order = 0;

var canvas = document.getElementById('project');
var context = canvas.getContext('2d');
var logo = document.getElementById('logo');

logo.onload = function() {
    canvas.width = logo.width;
    canvas.height = logo.height;

    context.drawImage(logo, 0, 0);
};

document.getElementById("btn_sub").addEventListener("click", function(event) {
    event.preventDefault();

    width = document.getElementById("form1").elements[0].value;
    height = document.getElementById("form1").elements[1].value;
    colors = document.getElementById("form1").elements[2].value;
    order = document.getElementById("form1").elements[3].value;

    logo.width = (width * 118) / 25.4;
    logo.height = (height * 118) / 25.4;

    canvas.width = (width * 118) / 25.4;
    canvas.height = (height * 118) / 25.4;

    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(logo, 0, 0);

The drawImage function is not taking into consideration the width and height of the image element. To make this work you can use this overload of the drawImage function context.drawImage(img,x,y,width,height) .

Like this for example, context.drawImage(logo, 0, 0, logo.width, logo.height) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM