如何裁剪当前为dataURL的图像?

时间:2019-07-22 23:08:06

标签: javascript canvas html5-canvas data-uri

我只能访问使用.toDataURL创建的图像。我似乎无法使用任何画布方法来重新种植它。

我正在尝试将dataURL复制到第二个画布,裁剪该画布,然后将该新裁剪的画布添加到现有元素(#screenshot)。

<body>
  <canvas id='canvas'></canvas>
  <canvas id='canvasCrop'></canvas>
</body>

<script>

  //existing data from an svg-to-canvas screen capture, taken from #canvas element   
  var canvas = document.getElementById('canvas'); 
  var dataURL = canvas.toDataURL('image/jpg');

  //get empty second canvas
  var myCanvas = document.getElementById('canvasCrop');
  var myContext = myCanvas.getContext('2d');

  var myImage;
  var img = new Image();
      img.src = dataURL;
      img.onload = () => {
        myContext.drawImage(img, 0, 0,1920,1080,0,0,1920,1080);
        myContext.save();

        //create a new data URL
        myImage = myCanvas.toDataURL();
      };

  //add to existing containers
  var screenshotImg = $("<img></img>");
  screenshotImg.attr("src", myImage);
  screenshotImg.prependTo("#screenshot");

</script>

要注意:当我将原始的“ dataURL”发送到屏幕截图元素时,它可以正常工作。一旦我尝试裁剪原始dataURL,它就会以某种方式损坏。我究竟做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

已修复代码,以反映下面的@Kaiido评论。

<body>
  <canvas id='canvas'></canvas>
  <canvas id='canvasCrop' width='1920px' height='1080px'></canvas>
</body>

<script>

  //existing data from an svg-to-canvas screen capture, taken from #canvas element   
  var canvas = document.getElementById('canvas'); 
  var dataURL = canvas.toDataURL('image/jpg');

  //get empty second canvas
  var myCanvas = document.getElementById('canvasCrop');
  var myContext = myCanvas.getContext('2d');

  var myImage;
  var img = new Image();
      img.src = dataURL;
      img.onload = () => {
        myContext.drawImage(img, 0, 0,1920,1080,0,0,1920,1080);
        myContext.save();

        //create a new data URL
        myImage = myCanvas.toDataURL();

        //add to existing containers
        var screenshotImg = $("<img></img>");
        screenshotImg.attr("src", myImage);
        screenshotImg.prependTo("#screenshot");
      };

</script>