无论如何从扩展的2d上下文获取dataurl?

时间:2017-07-29 13:58:41

标签: javascript html5 canvas

我有一个不同高度的画布。宽度根据视口宽度。现在画布用于使用toDataURL创建最终的png。但我需要固定分辨率的最终png。所以我必须从画布扩展2d上下文..但是如何从扩展的上下文中获取dataurl?我不会使用第二个画布。

*最终目标是保留一个画布(我的空间有限。例如640x480 div容器,而我需要的png是1920x1080 res)将在其上进行绘制。然后我需要一个缩放版本的绘制画布作为png

2 个答案:

答案 0 :(得分:0)

这就是答案。我自己弄清楚了。

canvas.toDataURL({format: 'png',multiplier: 1920/canvas.width}); 

谢谢您的回答。

答案 1 :(得分:-1)

所有元素都可以在页面外生活,您可以创建它们,根据需要使用它们,然后将它们取消,以便GC稍后进行清理。

使用屏幕外画布缩放图像的示例。

// Returns a new Image at size width, height
function resizeImage(image, width, height){
    const canvas = document.createElement("canvas"); // create a canvas element
    canvas.width = width;  // set its width and height
    canvas.height = height;
    // Draw the image scaled onto it
    canvas.getContext("2d").drawImage(image,0,0,width,height);
    // Create a new image element
    const scaledImage = new Image;
    // Set its src to the canvas content
    scaledImage.src = canvas.toDataURL(); // default mime type image/png
    // Return the new scaled image. 
    return scaledImage; // note Image may no have loaded at this point
    // The canvas is dereferences and will be cleaned up by GC very soon.
    // nobody will ever know it existed ;|
}
相关问题