HTML 画布可以绘制上传的图像
can html canvas draw uploaded images?
我正在尝试使用javascript创建一个上传图像大小调整功能。但是,使用文件阅读器将上传文件转换为 base64,画布上不会提供任何图像。相反,如果我使用外部图像并将其转换为 base64,则该函数就像一个魅力。怎么会这样?问题出在哪里?
这是我的代码,它很长。
//When changes are made to our input field
$ ('#input-file').change (function (evt) {
//The selected file is recovered
var file = evt.target.files [0];
//And processFiles function that will resize and send the file to the server is started
processFiles (file);
});
processFiles = function (file) {
var reader = new FileReader ();
//When the file has been completely read, the function will be executed ResizeImage
reader.onloadend = function (evt) {
//Reader.result represents our base64 encoded file
ResizeImage (reader.result, file);
};
//Allows you to play the file
reader.readAsDataURL (file);
};
ResizeImage = function (data, file) {
var fileType = file.type,
maxWidth = 960
maxHeight = 960;
//The file is loaded in a <img>
var image = new Image ();
image.src = data;
//Once the image is loaded, the following operations are performed
image.onload = function () {
//The ImageSize function calculates the final file size keeping the proportions
var size = ImageSize (image.width, image.height, maxWidth, maxHeight)
ImageWidth = size.width,
imageHeight = size.height,
//We create a canvas element
//canvas = document.createElement ('canvas');
canvas=document.getElementById('hahaha')
canvas.width = ImageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext ("2d");
//DrawImage will allow resizing the image
//This is our image here
var img=document.getElementById('haha')
ctx.drawImage (img, 0, 0, ImageWidth, imageHeight);
//Allows you to export the contents of the canvas element (our resized image) base64
data = canvas.toDataURL(fileType);
alert(data)
//All the elements used for resizing is suppressed
delete image;
delete canvas;
//SubmitFile (data);
}
};
//Function to resize an image keeping the proportions
ImageSize = function (width, height, maxWidth, maxHeight) {
var newWidth = width,
newHeight = height;
if (width> height) {
if (width> maxWidth) {
newHeight = maxWidth / width;
newWidth = maxWidth;
}
else {}
if (height> maxHeight) {
newWidth = maxHeight / height;
newHeight = maxHeight;
}
}
return {width: newWidth, height: newHeight};
};
你可以参考这个小提琴,http://jsfiddle.net/aliasm2k/tAum2/一些想法。它可能会对你有所帮助。这是我实现的一个小提琴,只是为了好玩而生成用户所选图像的缩略图。它使用文件读取器 API 选择文件,然后将缩略图加载到画布上。
就个人而言,我更喜欢经典的JS,而不是使用jQuery,并且使用了很多事件处理程序
oFileIn.addEventListener()
oFileReader.addEventListener()
oImage.addEventListener()
相关文章:
- 用图像而不是颜色填充对象(将图像绘制到画布上)
- 仅使用Chrome进行慢速图像绘制
- 将 SVG 图像绘制到 CanvasRenderingContext2D 中
- 为什么我不能将图像绘制到画布中
- 将许多新图像绘制到画布时内存泄漏
- Javascript - 加载GIF冻结,同时将图像绘制到画布(Phonegap/Cordova)
- 画布:绘制图像而不是将图像绘制到画布
- 将图像绘制到<画布>
- 在浏览器中识别完整的图像绘制
- 画布图像绘制失败
- 将图像绘制到画布上
- 如何在画布上为运动图像绘制多条路径
- 将图像绘制到画布有时不显示任何东西
- 修剪透明背景的图像绘制在画布与PHP或javascript
- Javascript将图像绘制在彼此之上
- 我可以将数组值插入到画布的图像绘制函数中吗?
- 画布上的图像绘制比原始尺寸大
- 画布图像绘制不工作
- 将预先加载的图像绘制到画布中
- javascript从缓冲区(nodejs/socket.io)将图像绘制到html中