是否可以将画布下载为具有自定义尺寸的图像?

dvs*_*spy 2 html javascript jquery canvas html5-canvas

我正在尝试将画布下载为图像。我的画布高度是 500px,宽度也是 500px,但我想下载 700px 的图像,而不改变画布大小。

我的代码如下:

    <div class="surface">
     <canvas id="myCanvas" height="500" width="500"></canvas>
    </div>

<a id="downloadImgLink" onclick="$('#downloadImgLink').attr('href', myCanvas.toDataURL());" download="MyImage.png" href="#" target="_blank" class="btn btn-danger">Download</a>
Run Code Online (Sandbox Code Playgroud)

上面的代码是下载高度和宽度为 500px 的图像,但我需要 700px 或任何自定义尺寸的图像,而不改变画布尺寸。

有没有可能的方法可以将任何画布下载为具有自定义尺寸的图像,而无需调整画布大小?

Kai*_*ido 5

toDataURL()canvas 元素(和)的任何内置导出方法都没有大小参数toBlob()
但是,您可以非常轻松地编写自己的实现:

正如markE在评论中提到的,ctx.drawImage()有一个调整绘制图像大小的选项ctx.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destinationX, destinationY, destinationWidth, destinationHeight);
您还可以传递画布元素作为其第一个image参数。

然后你可以写这样的东西:

canvas.resizeAndExport = function(width, height){
  // create a new canvas
  var c = document.createElement('canvas');
  // set its width&height to the required ones
  c.width = width;
  c.height = height;
  // draw our canvas to the new one
  c.getContext('2d').drawImage(this, 0,0,this.width, this.height, 0,0,width, height);
  // return the resized canvas dataURL
  return c.toDataURL();
  }

// draw a simple rectangle for the example
canvas.getContext('2d').fillRect(0,0,50,200);
// create an image that will get our resized export as src
var img = new Image();
img.src = canvas.resizeAndExport(40, 40);
document.body.appendChild(img);
Run Code Online (Sandbox Code Playgroud)
img, canvas{border: 1px solid}
Run Code Online (Sandbox Code Playgroud)
<canvas height="200" width="200" id="canvas"></canvas>
Run Code Online (Sandbox Code Playgroud)