我试图编写一个代码来在"预览图像上写一个多边形"对于类型文件输入。问题:当我点击画布绘制多边形的第一个点时,图像消失了......为什么?
$(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 = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $('<img>', { src: e.target.result });
var canvas = $('#canvas')[0];
context = canvas.getContext('2d');
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
$.fn.canvasAreaDraw = function (options) {
this.each(function (index, element) {
init.apply(element, [index, element, options]);
});
}
var init = function (index, input, options) {
var points, activePoint, settings;
var $canvas, ctx, image;
var draw, mousedown, stopdrag, move, resize, reset, rightclick, record;
$(document).ready(function () {
$(input).after('<br>', $canvas, '<br>');
$('canvas').on('mousedown', mousedown);
$('canvas').on('mouseup', stopdrag);
context.drawImage(this, 0, 0);
});
points = [];
mousedown = function (e) {
var x, y, dis, lineDis, insertAt = points.length; //points length = numero de puntos
if (!e.offsetX) {
e.offsetX = (e.pageX - $(e.target).offset().left);
e.offsetY = (e.pageY - $(e.target).offset().top);
}
x = e.offsetX;
y = e.offsetY;
points.splice(insertAt, 0, Math.round(x), Math.round(y));
draw();
return false;
}
draw = function () {
context.canvas.width = context.canvas.width;
context.globalCompositeOperation = 'destination-over';
context.fillStyle = 'rgb(255,255,255)' //color background punto
context.strokeStyle = 'rgb(255,20,20)';
context.lineWidth = 1;
context.beginPath();
context.moveTo(points[0], points[1]);
for (var i = 0; i < points.length; i += 2) {
alert("1111");
context.fillRect(points[i] - 2, points[i + 1] - 2, 4, 4);
context.strokeRect(points[i] - 2, points[i + 1] - 2, 4, 4);
if (points.length > 2 && i > 1) {
context.lineTo(points[i], points[i + 1]);
}
}
context.closePath();
context.stroke(); //dibuja la linea entre los puntos
};
}
$(document).ready(function () {
$('canvas').canvasAreaDraw();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<canvas id="canvas" width="500px" height="300px"></canvas>
<input type="file" id="file-input">
&#13;
答案 0 :(得分:1)
这是因为您正在使用以下行清除画布:
context.canvas.width = context.canvas.width;
只需将此行替换为drawImage()
,您可以将图像重绘到画布上而不是清除它。
每次存储的任何点都必须重新绘制。