如何从较小的画布上获得高分辨率图像?

Nik*_*ara 2 html javascript canvas html5-canvas

我在我的网络应用程序中使用一张画布,其实际高度和宽度均为 500 像素。我在屏幕上将此画布显示为 500 像素正方形,但我希望从该画布导出图像为 1600 像素正方形。我尝试过下面的代码,但没有成功。

canvas.width = 1600;
canvas.style.width = 500;
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

Bli*_*n67 7

您可以让画布以 500 像素显示,同时仍具有 1600 像素的分辨率。显示尺寸和分辨率是独立的。对于分辨率,您可以设置画布的宽度和高度属性。对于显示尺寸,您可以设置画布样式的宽度和高度属性。

// create a canvas or get it from the page
var canvas = document.createElement("canvas");
// set the resolution (number of pixels)
canvas.width = canvas.height = 1600;
// set the display size
canvas.style.width = canvas.style.height = "500px";
// get the rendering context
var ctx = canvas.getContext("2d");
Run Code Online (Sandbox Code Playgroud)

为了使渲染与显示尺寸相匹配,您需要放大所有渲染。您可以通过将变换比例设置为画布分辨率除以显示尺寸来完成此操作

var scale = 1600 / 500; // get the scale that matches display size 
ctx.setTransform(scale,0,0,scale,0,0);
Run Code Online (Sandbox Code Playgroud)

现在,当您渲染到画布时,您将使用屏幕尺寸坐标。

ctx.fillRect(0,0,500,500); // fill all of the canvas.
ctx.fillStyle = "red";  // draw a red circle 100 display pixels in size.
ctx.beginPath();
ctx.arc(250,250,100,0,Math.PI * 2);
ctx.fill();
Run Code Online (Sandbox Code Playgroud)

然后保存画布时,无论使用什么方法,只要不是屏幕捕获,保存的画布都将是 1600 x 1600,并且所有渲染都将正确定位和成比例