图像文件到可汗学院代码

Image file to Khan Academy code

所以这是我的代码,应该将图像转换为可汗学院的像素艺术:

<button onclick="Restart()">Reset</button><br />
<p></p>
<form id="myFile">
<input accept="image/*" onchange="openFile(event)" type="file" /><br />
<br /></form>
<input id="Input" max="200" min="1" name="points" oninput="Update()" type="range" /><br />
<div id="Value">
Image size: 100</div>
<canvas height="100" id="myCanvas" style="border: 1px solid #000000;" width="100">Sorry but your browser does not support the HTML canvas tag.  You might need to update your browser.</canvas><br />
Your Code<br />
&nbsp; &nbsp; &nbsp; ||<br />
&nbsp; &nbsp; &nbsp; \/<br />
<textarea cols="100" id="myTA" placeholder="Follow the instructions to get your code." readonly="" rows="10"></textarea>
<script>
pix = 100;
function Update(){
    var Input = document.getElementById('Input').value;
    document.getElementById('Value').innerHTML = 'Image size: '+Input;
    pix = Input;
    var c = document.getElementById("myCanvas");
    c.width = pix;
    c.height = pix;
};
var openFile = function(event) {
    var input = event.target;
    var reader = new FileReader();
    var Input = document.getElementById('Input');
    Input.disabled = true;
    reader.onload = function(){
        var dataURL = reader.result;
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        var img = document.createElement("img");
        img.id = 'myImg';
        img.src = dataURL;
        ctx.drawImage(img, 0, 0, pix, pix);
        var tex = ctx.getImageData(0, 0, pix, pix).data;

        document.getElementById('myTA').innerHTML = '//Generator (by me) http://kennys-programs.blogspot.com/p/hi.html\n\
var imgData = ['+tex+'];\n\
var d = 0;\n\
scale(width/'+pix+', height/'+pix+');\n\
background(255, 255, 255, 0);\n\
for(var i = 0; i < imgData.length; i+=4){\n\
    stroke(imgData[i], imgData[i+1], imgData[i+2], imgData[i+3]);\n\
    point(i/4, 0);\n\
    d += 1;\n\
    if(d === '+pix+'){\n\
        translate(-'+pix+', 1);\n\
        d-='+pix+';\n\
    }\n\
}';
    };
    reader.readAsDataURL(input.files[0]);
};
function Restart(){
    window.location.reload();
};
</script>

它在 Chrome 和 Firefox 中运行良好,但在 Safari 中它输出:

//Generator (by me) http://kennys-programs.blogspot.com/p/hi.html
var imgData = [[object Uint8ClampedArray]];
var d = 0;
scale(width/100, height/100);
background(255, 255, 255, 0);
for(var i = 0; i < imgData.length; i+=4){
    stroke(imgData[i], imgData[i+1], imgData[i+2], imgData[i+3]);
    point(i/4, 0);
    d += 1;
    if(d === 100){
        translate(-100, 1);
        d-=100;
    }
}

谁能帮我解决这个问题?在 Safari 中它应该输出一个带有 RGBA 值的数组,而不是输出文本 object Uint8ClampedArray.

尝试

var tex = JSON.stringify(ctx.getImageData(0, 0, pix, pix).data);

如果不行试试

var tex = Array.prototype.slice.call(ctx.getImageData(0, 0, pix, pix).data);