HTML5画布绘图不清除&校准关闭

时间:2017-05-13 13:20:19

标签: jquery html5 canvas drawing

清除按钮不会在点击时清除画布。但是,当我按下清除后单击回到画布上时,画布本身会清除。

我遇到的另一个问题是光标不是路径的起点。

这是我的代码:

var canvas = document.getElementById('doodle-canvas');
var context = canvas.getContext('2d');
var radius = 10;
var dragging = false;

canvas.width = document.getElementById('doodle-canvas').clientWidth;
canvas.height = document.getElementById('doodle-canvas').clientHeight;

context.lineWidth = radius*2;


var clearButton = document.getElementById('doodle-bin');

/* CLEAR CANVAS */
function clearCanvas(){
	context.clearRect(0, 0, canvas.width, canvas.height);
}

clearButton.addEventListener('click', clearCanvas);



var putPoint = function(e) {
	
	if (dragging) {
		context.lineTo(e.clientX, e.clientY);
		context.stroke();
		context.beginPath();
		context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2);
		context.fill();
		context.beginPath();
		context.moveTo(e.clientX, e.clientY);
	}
}

var engage = function(e) {
	dragging = true;
	putPoint(e);
}
var disengage = function() {
	dragging = false;
	context.beginPath();
}

canvas.addEventListener('mousedown', engage);
canvas.addEventListener('mousemove', putPoint);
canvas.addEventListener('mouseup', disengage);

1 个答案:

答案 0 :(得分:0)

我发现清除按钮没有问题。它确实清除了画布,

对于游标问题,请分别使用e.offsetXe.offsetY代替e.clientXe.clientY

var clearButton = document.getElementById('doodle-bin');
var canvas = document.getElementById('doodle-canvas');
var context = canvas.getContext('2d');
var radius = 10;
var dragging = false;

canvas.width = document.getElementById('doodle-canvas').clientWidth;
canvas.height = document.getElementById('doodle-canvas').clientHeight;

/* CLEAR CANVAS */
function clearCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}

clearButton.addEventListener('click', clearCanvas);

var putPoint = function (e) {
    if (dragging) {
        context.lineTo(e.offsetX, e.offsetY);
        context.lineWidth = radius * 2;
        context.stroke();
        context.beginPath();
        context.arc(e.offsetX, e.offsetY, radius, 0, Math.PI * 2);
        context.fill();
        context.beginPath();
        context.moveTo(e.offsetX, e.offsetY);
    }
};

var engage = function (e) {
    dragging = true;
    putPoint(e);
};

var disengage = function () {
    dragging = false;
    context.beginPath();
};

canvas.addEventListener('mousedown', engage);
canvas.addEventListener('mousemove', putPoint);
canvas.addEventListener('mouseup', disengage);
body{margin:10px 0 0 0;overflow:hidden}canvas{margin-top:5px;border:1px solid #e4e6e8}
<button id="doodle-bin">Clear</button>
<canvas id="doodle-canvas" width="635" height="182" style="border:1px solid #d3d3d3"></canvas>