我为图片完成了一次上传并将图片放到了画布上,这里是DEMO。现在,问题在于,当我上传图片然后我想上传另一张图片时,上一张图片仍然保留在下面。
这是我的代码:
JS:
var canvas = document.getElementById('main');
var ctx = canvas.getContext('2d');
var fileInput = document.getElementById('fileInputTest');
fileInput.addEventListener('change', imageLoader, false);
function imageLoader() {
var reader = new FileReader();
reader.onload = function(event) {
img = new Image();
img.onload = function() {
var MAX_WIDTH = 150;
var MAX_HEIGHT = 150;
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;
}
}
ctx.drawImage(img, 0, 0, width, height);
}
img.src = reader.result;
}
reader.readAsDataURL(fileInput.files[0]);
}
HTML:
<input type="file" id="fileInputTest" />
<canvas id="main" width="150" height="150"></canvas>
CSS:
#main {
border: 2px dotted black;
border-radius: 5px position: absolute;
}
答案 0 :(得分:0)
只需在上下文中绘制图像之前添加它。
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, width, height);
您必须在绘制图像之前清除画布区域。