简体   繁体   中英

HTML canvas dynamic image width and height

I am trying to create multiple canvas and placing array of images in each canvas. Kindly correct me where I am wrong. Following is my code.

var mywidth, myheight;
$(function(){
    var Images = ['1.jpg','2.jpg','3.jpg','4.png','5.jpg']
    var imageLength = Images.length;


    function doit(){
        var image = new Image();
        var canvas = document.getElementById("div"+i).getContext("2d");
        image.onload = function divId() {
            // Done loading, now we can use the image
            canvas.drawImage(image, 0, 0, mywidth, myheight);
        };
        image.src = Images[i];
    }

    for(i=0;i<imageLength;i++){
        var img = new Image();
        img.src = Images[i];
        mywidth = (img.width/3);
        myheight = (img.height/3);
        console.log(mywidth + ' x ' + myheight);
        $('.result').append('<canvas id="div'+i+'" width="'+mywidth+'" height="'+myheight+'"></canvas>');
        doit();
    }
});

grid is generating but images does not starch as per the canvas size. canvas width and height is its image 33.336%. kindly help.

The canvas needs to be created after the image loads.

var mywidth, myheight;
$(function(){
    var Images = ['1.jpg','2.jpg','3.jpg','4.png','5.jpg']
    var imageLength = Images.length;


    function doit(i){
        var image = new Image();

        image.onload = function() {
            mywidth = (image.width/3);
            myheight = (image.height/3);
            console.log(mywidth + ' x ' + myheight);
            $('.result').append('<canvas id="div'+i+'" width="'+mywidth+'" height="'+myheight+'"></canvas>');
            var canvas = document.getElementById("div"+i).getContext("2d");
            canvas.drawImage(image, 0, 0, mywidth, myheight);
        };
        image.src = Images[i];
    }

    for(i=0;i<imageLength;i++){
        doit(i);
    }
});

这就是它的样子

this is how it looks like. Every picture has its own width and height. all i'm doing .grid = 100%, grid-item = 33.33% of 100%. lets say first grid-item = 400px then canvas width = 100% of first grid. now placing image to canvas 1, width will 400px hope u understand my point

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