How to load images from json object on canvas imag

2020-05-02 19:26发布

问题:

Need to plot alphaball.png image on different positions on canvas image. Positions (x and y co-ordinates) need to pass from data json object. with the code mention alphaball.png is not visible. what can be done?

//JSON object

data = [{
         "x": ["200"],
         "y": ["200"]

     }, {
         "x": ["150"],
         "y": ["150"]
     }, {
         "x": ["300"],
         "y": ["300"]
     }


 ];


window.onload = function(){ 
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
var dataJSON = data || []
        var files = ["gkhead.jpg", "marker.png"],
        images = [],
        numOfFiles = files.length,
        count = numOfFiles;

        /// function to load all images in one go
        function loadImages() {
            /// go through array of file names
            for(var i = 0; i < numOfFiles; i++) {
                /// create an image element
                var img = document.createElement('img');
                /// use common loader as we need to count files
                img.onload = imageLoaded;
                console.log(imageLoaded);
                //img.onerror = ... handle errors
                img.src = files[i];
                //console.log(img.src);
                /// push image onto array in the same order as file names
                images.push(img);
                //console.log(images);
            }
        }
        loadImages();
        function imageLoaded(e) {
            /// for each successful load we count down
            count--;
            if (count === 0) 
            start(); //start when nothing more to count
        }
        function start() {
        context.drawImage(images[0], 0, 0, 400*scaleValue, 400*scaleValue); 
           for(var i = 0, pos; pos = dataJSON[i]; i++) {
               /// as we know the alpha ball has index 1 we use that here for images
               context.drawImage(images[1], pos.x, pos.y, 40/scaleValue, 40/scaleValue);
           }
        }

function draw1(scaleValue, dataJSON){
        loadImages();

        context.save();     
        context.setTransform(1,0,0,1,0,0)   
        context.globalAlpha = 0.5;                      
        context.clearRect(0, 0, canvas.width, canvas.height);   
        context.restore();          
        context.save(); 
        context.drawImage(images[0], 0, 0, 400*scaleValue, 400*scaleValue); 

        context.scale(scaleValue, scaleValue);
        start();

        context.restore();
    }; 
    draw1(scaleValue, dataJSON);

        var scaleValue = 1;
        var scaleMultiplier = 0.8;
        var startDragOffset = {};
        var mouseDown = false;          
        // add button event listeners
        document.getElementById("plus").addEventListener("click", function(){           
            scaleValue /= scaleMultiplier;              
            draw1(scaleValue, dataJSON);            
        }, false);
         document.getElementById("minus").addEventListener("click", function(){
            scaleValue *= scaleMultiplier;
            draw1(scaleValue, dataJSON);    
        }, false);
        document.getElementById("original_size").addEventListener("click", function(){
            scaleValue = 1;
            draw1(scaleValue, dataJSON);
        }, false);

回答1:

I am not sure why you load the alpha ball several times, but you can collect the file loading into a common place:

/// set up some variables to contain images and count
var files = ["gkhead.jpg", "alphaball.png"],
    images = [],
    numOfFiles = files.length,
    count = numOfFiles;

/// function to load all images in one go
function loadImages() {

    /// go through array of file names
    for(var i = 0; i < numOfFiles; i++) {

        /// create an image element
        var img = document.createElement('img');

        /// use common loader as we need to count files
        img.onload = imageLoaded;
        //img.onerror = ... handle errors
        img.src = files[i];

        /// push image onto array in the same order as file names
        images.push(img);
    }
}
function imageLoaded(e) {

    /// for each successful load we count down
    count--;
    if (count === 0) start(); //start when nothing more to count
}

Now you can draw the balls:

function start() {
   for(var i = 0, pos; pos = dataJSON[i]; i++) {
       /// as we know the alpha ball has index 1 we use that here for images
       context.drawImage(images[1], pos.x, pos.y, 40/scaleValue, 40/scaleValue);
   }
}