对复制图像进行的更改也会对原始图像进行更改。(js)

时间:2019-12-08 07:19:26

标签: javascript

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

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>

1 个答案:

答案 0 :(得分:0)

我什么都不知道,但是只要这样做,您就会在画布上得到灰色图像

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