我可以将图像上传到浏览器并将其转换为BLOB。之后,我尝试将它绘制到我的画布中,但它没有得到识别。我有一种感觉,这是我想念的小东西,但我看不到它。任何帮助都会很棒!
var resize_img =
function(){
var file = document.getElementById("add_img").files;
// add in file type checker
// Create img element to PREVIEW
var img = document.createElement("img");
img.src = window.URL.createObjectURL(file[0]);
// Draw image to CANVAS
var canvas_e = document.getElementById("canvas_img");
var ctx = canvas_e.getContext("2d");
ctx.drawImage(img, 0, 0);
//Resize Image
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas_e.width = width;
canvas_e.height = height;
ctx.drawImage(img, 0, 0, width, height);
//Push Data
var dataurl = canvas_e.toDataURL("image/png");
console.log(dataurl);
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!-- CSS -->
<link href="css/main.css" rel="stylesheet" type="text/css" >
</head>
<body>
<input type="file" id="add_img" onchange="resize_img()">
<canvas id="canvas_img"></canvas>
<!-- JS -->
<script src="js/main.js" type="text/javascript"></script>
</body>
</html>
答案 0 :(得分:2)
将画布代码放在img.onload = function(){....}
中