javascript:在Image加载后计算并返回值

时间:2016-09-03 14:53:39

标签: javascript image asynchronous return onload

我已经检查了对异步javascript行为的多个响应并尝试了回调,然后尝试使用promises,但是我想在这里发送SoS请求:/

因为通常第一个答案是(“你想做什么?”)

我必须找出一个Image中的所有非空或透明像素。(有点像一个掩码)并给它们一个二进制算术数字的数组。

我的课程简而言之:

  • 获取图片网址并从中创建<?php function onereplace($str,$replaced_character){ $spt = str_split($str,1); for($i=0; $i <= (count($spt) - 1) ; $i++){ if($spt[$i] == $replaced_character){ unset($spt[$i]); break; } } return implode('',$spt); } if(isset($_GET['zig'])){ $file = file("../01912424773.txt"); $post = $_GET['zig'] ; $length = strlen($post); $output[] = '<hr><h3 style="color:#e85151;" id="resulty">Result/Results</h3></hr>' ; foreach($file as $value){ $value = trim($value); $value_proxy = strtoupper(trim($value)); if(strlen(trim($value)) == $length){ for($i=0;$i<=($length - 1); $i++){ $data = strtoupper($post[$i]); $value_proxy = onereplace($value_proxy,$data); } //echo "value=".$value_proxy."<br>"; if(trim($value_proxy) == ''){ $output[] = '<p>'.$value."</p>" ; } } // end if set_time_limit(0); } // end foreach foreach($output as $result){ echo $result; } } ?>
  • 它创建一个Canvas并将其添加到DOM
  • new Image()中,它在画布上绘制图像
  • 在图像在画布上之后,它会扫描每个像素的颜色并返回一个数据数组。

我的问题是强制计算等待,直到加载图像。我尝试过这样的事情:

image.onLoad()

但是,在return getDataArray(image.onLoad()= function(){ // ...init things... })); 发生之前,它会进入getDataArray函数。

我要休息一下,然后走出去,因为我没有富有成效的想法。

这是原始功能:

image.onLoad

这是结果

请求计算

getImageScan: function() {
    this.myImage.src = imageScanner.imgUrl;
    var is = this;
    return  is.getArrayFromCanvas(this.myImage.onload = function () {
        is.imageHeight = is.myImage.height;
        is.imageWidth = is.myImage.width;
        is.appendCanvasToBody();
        is.initGraphicalContent();
        is.drawImageOnCanvas();
        console.log("image is loaded");
    })
},

getArrayFromCanvas: function () {
    console.log("request for calculations");
    var booleanJson = this.getJsonFromCanvas()
    return this.getBinaryArithmeticFromBooleans(booleanJson);
}

图片已加载

如果你想要更多的信息(这是我的私人项目在松弛时间,所以没有版权问题),这里是整个* .js:

https://github.com/Vilkaz/gridToImage/blob/master/web/resources/js/imageScanner.js

1 个答案:

答案 0 :(得分:1)

尽管没有参数,但您尝试将内容传递给getArrayFromCanvas。我不明白为什么你这样做,但我想你想要这样的事情:

getImageScan: function(callback) {
  this.myImage.src = imageScanner.imgUrl;
  var is = this;
  this.myImage.onload = function () {
    is.imageHeight = is.myImage.height;
    is.imageWidth = is.myImage.width;
    is.appendCanvasToBody();
    is.initGraphicalContent();
    is.drawImageOnCanvas();
    console.log("image is loaded");
    callback(is.getArrayFromCanvas());
  }
}

上面的异步行为和原始代码之间的一个区别是getImageScan会立即返回,并且稍后会调用回调到&#34;返回&#34;结果。