canvas imageData manipulation

canvas imageData manipulation

本文关键字:manipulation imageData canvas      更新时间:2023-09-26

我正在玩画布imageData,我有一些速度问题。我正在做的是

$(document).ready(function(){
        loadCanvas();
        myImageData();
});
function loadCanvas(){
    canvas = document.getElementById('myCanvas');
    context = canvas.getContext('2d')
    image = new Image();
    image.src = '/static/images/teeth1.jpg';
    image.onload = function (){
        imageWidth = image.width;
        imageHeight = image.height;
        context.drawImage(image, 0, 0, image.width, image.height);
        imageData = myImageData(context, image);
        pixels = imageData.data;
        console.log(pixels);
        console.log(pixels.length);
        console.log(imageData);  
        //Changing the value of each pixel
        for (var y=0; y<=imageHeight; ++y){
            for (var x=0; x<=imageWidth; ++x){
                index = (y*imageWidth + x) * 4;
                pixels[index] += 30;
                pixels[++index] += 30;
                pixels[++index] += 30;
            }
        }                       
    }   
}
function myImageData(context){
    console.log("width: "+image.width+", height:"+image.height)
    return context.getImageData(0, 0, image.width, image.height);
}

当我从chrome的控制台执行onload函数之外的上述代码,它的工作速度非常快。但是当在onload函数内执行双精度for时(就像现在一样),它会挂起。为什么呢?是因为它在onload中吗?我怎么能确保图像是完全加载之前执行双fors(所以把它们单独的onload函数之外)?

// Define functions before using them (Good to)
function loadCanvas(){     
    var canvas = document.getElementById('myCanvas'); // Define variables!
    var context = canvas.getContext('2d');
    var image = new Image();     
    image.onload = function (){
        var imageWidth  = image.width;  // Variables again!
        var imageHeight = image.height;
        context.drawImage(image, 0, 0, imageWidth, imageHeight );
        var imageData = myImageData(context, image); // Variables!
        var pixels = imageData.data;
        console.log(pixels);
        console.log(pixels.length);
        console.log(imageData);  
        //Changing the value of each pixel
        for (var y=0; y<=imageHeight; ++y){
            for (var x=0; x<=imageWidth; ++x){
                var index = (y*imageWidth + x) * 4;
                pixels[index] += 30;
                pixels[++index] += 30;
                pixels[++index] += 30;
            }
        }                      
    };
    image.src = '/static/images/teeth1.jpg'; // Set src here
}
function myImageData(ctx, img){  // Pass the actual image as argument
    console.log("width: "+img.width+", height:"+img.height);
    return ctx.getImageData(0, 0, img.width, img.height);
}
$(document).ready(function(){
    loadCanvas();    // has myImageData() so...
    //myImageData(); // why??
});