我想使用浏览按钮在画布中添加图像。我尝试做某事,我可以使用浏览按钮但不在画布中添加图像。我该怎么办?
<div style="float:left;"><canvas id="c" width="800" height="800"></canvas></div>
<p onclick="jQuery('#file').trigger('click');">Select a file</p>
<input type="file" id="file" name="file" />
答案 0 :(得分:0)
这样的东西?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
</head>
<body>
<script>
$(function() {
$('#file-input').change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = loadFile;
reader.readAsDataURL(file);
});
function loadFile(e) {
var $img = $('<img>', { src: e.target.result });
var canvas = $('#canvas')[0];
var context = canvas.getContext('2d');
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<div style="float:bottom"><input type="file" id="file-input"><div>
<div style="float:left">
<canvas id="canvas" width="800px" height="800px"></canvas>
</div>
</body>
</html>