我正在玩画布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函数中执行double for(就像它现在一样)时,它会挂起。这是为什么?是因为它在onload中吗?如何在执行double fors之前确保图像已满载(所以要将它们单独放在onload函数之外)?
答案 0 :(得分:1)
// 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??
});