我的小提琴有问题。我正在尝试从PC上传图片,然后对其进行切片,然后将所有方块打乱。我设法创建了上传图像的功能,而其他功能则可以从网络上对图像进行切片和混洗,但是我无法使它们协同工作。你能帮我吗?该代码是下面的代码:



$(function () {
    $(":file").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
        }
    });
});

function imageIsLoaded(e) {
    $('#myImg').attr('src', e.target.result);
}


var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var rows=6;
var cols=6;

var img=new Image();
img.onload=start;
img = document.getElementById("myImg");
function start(){

  var iw=canvas.width=img.width;
  var ih=canvas.height=img.height;
  var pieceWidth=iw/cols;
  var pieceHeight=ih/rows;

  var pieces = [
    {col:0,row:0},
    {col:1,row:0},
    {col:2,row:0},
    {col:3,row:0},
    {col:4,row:0},
    {col:5,row:0},
    {col:0,row:1},
    {col:1,row:1},
    {col:2,row:1},
    {col:3,row:1},
    {col:4,row:1},
    {col:5,row:1},
    {col:0,row:2},
    {col:1,row:2},
    {col:2,row:2},
    {col:3,row:2},
    {col:4,row:2},
    {col:5,row:2},
    {col:0,row:3},
    {col:1,row:3},
    {col:2,row:3},
    {col:3,row:3},
    {col:4,row:3},
    {col:5,row:3},
    {col:0,row:4},
    {col:1,row:4},
    {col:2,row:4},
    {col:3,row:4},
    {col:4,row:4},
    {col:5,row:4},
    {col:0,row:5},
    {col:1,row:5},
    {col:2,row:5},
    {col:3,row:5},
    {col:4,row:5},
    {col:5,row:5},
  ]
    shuffle(pieces);

    var i=0;
    for(var y=0;y<rows;y++){
    for(var x=0;x<cols;x++){
    var p=pieces[i++];
  ctx.drawImage(
    // from the original image
    img,
    // take the next x,y piece
    x*pieceWidth, y*pieceHeight, pieceWidth, pieceHeight,
    // draw it on canvas based on the shuffled pieces[] array
    p.col*pieceWidth, p.row*pieceHeight, pieceWidth, pieceHeight
  );
}}


}

function shuffle(a){
  for(var j, x, i = a.length; i; j = Math.floor(Math.random() * i), x = a[--i], a[i] = a[j], a[j] = x);
  return a;
}

body{ background-color: ivory; padding:10px; }
#canvas{border:0px solid ;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<input type='file' />
<img id="myImg" src="#" alt="your image" />
<canvas id="canvas" width=1080 height=1080></canvas>

最佳答案

在代码中,先设置onload处理程序,然后再覆盖img变量。在此代码中,由于第3行,前2行实际上是无效代码。

var img=new Image();
img.onload=start;
img = document.getElementById("myImg");


相反,您应该只获取元素并在其后添加处理程序。

var img = document.getElementById("myImg");
img.onload=start;

07-28 01:35