画布未更新

时间:2018-01-08 19:26:06

标签: javascript canvas synaptic.js

出于学习目的,我尝试复制此example。 一切似乎都很好,但由于某些原因,画布没有更新。每当代码执行,终止或完成画布总是0px宽度0px高度。也许我犯了一些错误(我肯定应该说),但我不知道会出现什么问题。

// create the network
const { Layer, Network } = window.synaptic;

var inputLayer = new Layer(2);
var hiddenLayer = new Layer(15);
var outputLayer = new Layer(3);

inputLayer.project(hiddenLayer);
hiddenLayer.project(outputLayer);

var myNetwork = new Network({
    input: inputLayer,
    hidden: [hiddenLayer],
    output: outputLayer
});

var imgRef = new Image();
imgRef.src = './reference.png';
var width = imgRef.width;
var height = imgRef.height;
imgRef.setAttribute('crossOrigin', '');

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var canvasd = ctx.getImageData(0 , 0, width, height)

var refCanvas = document.getElementById('canvas1');
var rctx = canvas.getContext('2d');

var refHTML = document.getElementById('reference');

rctx.drawImage(refHTML, 0, 0);

var ref = rctx.getImageData(0, 0, width, height);
imageData = ctx.getImageData(0,0,width,height);

// train the network - learn XOR
var learningRate = .1;

for (var i = 0; i < 20000; i++)
    {

        for (var x=0;x<width;x++){
            for(var y=0;y<height;y++){

                myNetwork.activate([x/width, y/height]);
                myNetwork.propagate(learningRate, pixel(ref.data, x,y));




                var rgb = myNetwork.activate([x/width,y/height]);

                imageData.data[((height * y) + x) * 4] = (rgb[0] )* 255;
            imageData.data[((height * y) + x) * 4 + 1] = (rgb[1] ) * 255;
            imageData.data[((height * y) + x) * 4 + 2] = (rgb[2] ) * 255;
            imageData.data[((height * y) + x) * 4 + 3] = 1;
            }
        }

        ctx.putImageData(imageData,0,0);


    }


function pixel(data,a,b){

    var red = data[((height*b)+a)*4];
    var green = data[((height*b)+a)*4 + 1];
    var blue = data[((height*b)+a)*4 + 2]

    return [red/225, green/225, blue/225]
}

代码在Firefox上测试。

1 个答案:

答案 0 :(得分:0)

var canvas = document.getElementById('canvas');行上,您正在从页面中选择一个画布元素。有时这可能会在JS定义的宽度/高度和CSS定义的宽度/高度之间产生冲突。

尝试:

var canvas = document.createElement('canvas');
canvas.height = y;
canvas.width = x;