使用画布调整图像大小

时间:2014-07-03 23:57:46

标签: javascript html5 canvas

您想使用画布调整图片大小,但无法使其工作...... 我希望图像为100px * 100px,有什么方法可以解决这个问题吗? 我试过谷歌和尝试但不能让它工作......

我也尝试在css中更改img大小,但这也没有帮助,请帮助我!

function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;


// Copy the image contents to the canvas
ctx.drawImage(img, 0, 0);

// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");

return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

}

我也意识到我需要旋转它我该怎么做?

1 个答案:

答案 0 :(得分:0)

你必须得到宽度的比例并将其应用到高度。

var ratio = 100 / img.width; // 100 for desired width in px
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;

ctx.drawImage(img, 0,0, canvas.width, canvas.height);

在手机上键入,原谅小错误。

相关问题