我复制了图像并对其进行了更改。原始图像也以某种方式也发生了变化,这是不应该的。
有人知道如何解决吗?

Text

<script>
var thePhoto;
var theImage = null;
var theCanvas = null;
function upload(){
  thePhoto = document.getElementById("orgPhoto");
  theImage = new SimpleImage(thePhoto);
  theCanvas = document.getElementById("mycanvas");
  theImage.drawTo(theCanvas);
}
function makeGray(){
  if (theCanvas == null || ! theCanvas.complete()){
    alert('no photo');
  }else{
    var GrayImage = new SimpleImage(thePhoto);
    for (var pixel of GrayImage.values()){
      var avg = (pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;
      pixel.setRed(avg);
      pixel.setGreen(avg);
      pixel.setBlue(avg);
    }
    GrayImage.drawTo(theCanvas);
  }
}
</script>

最佳答案

我没有得到所有这些的全部,但是仅通过这样做,您将在画布上得到灰色图像

thePhoto = document.getElementById("orgPhoto");
  theCanvas = document.getElementById("mycanvas");
  var ctx = theCanvas.getContext("2d");
  ctx.filter='grayscale(100%)';
  ctx.drawImage(thePhoto, 20,20);

09-07 18:52