javascript 将画布输出图像调整为特定大小(宽/高)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23481210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resize the canvas output image to a specific size (width/height)
提问by Kivylius
I have a big canvas (5000x5000
) and I want to take a picture of it and create a thumbnail on client side. I can capture the image using canvas.toDataURL
but how do i re-size it? Do i have to create an new $("<canvas></canvas>")
element and then put that image inside and run the canvas2.toDataURL();
Can anyone help me with this? I can't get my head around it how to do it.
我有一个大画布 ( 5000x5000
),我想给它拍照并在客户端创建一个缩略图。我可以使用捕获图像,canvas.toDataURL
但如何重新调整大小?我是否必须创建一个新$("<canvas></canvas>")
元素,然后将该图像放入其中并运行canvas2.toDataURL();
任何人都可以帮助我吗?我不知道该怎么做。
var canvas = document.getElementById("main");
var ctx = canvas.getContext("2d");
var tumbnail64 = null;
var image = new Image();
image.src = canvas.toDataURL();
image.onload = function() {
$c2 = $("<canvas></canvas>");
$c2[0].width=100;
$c2[0].height=100;
$c2[0].getContext("2d");
$c2[0].drawImage(image, 0, 0,100,100);
tumbnail64 = $c2[0].toDataURL();
};
回答by Nick
Something like this should work, given you don't have security restrictions on the original canvas element:
鉴于您对原始画布元素没有安全限制,这样的事情应该可以工作:
var resizedCanvas = document.createElement("canvas");
var resizedContext = resizedCanvas.getContext("2d");
resizedCanvas.height = "100";
resizedCanvas.width = "200";
var canvas = document.getElementById("original-canvas");
var context = canvas.getContext("2d");
resizedContext.drawImage(canvas, 0, 0, 200, 100);
var myResizedData = resizedCanvas.toDataURL();