我正在构建一个绘画工具应用程序。我正在使用两个画布。一种用于加载背景图像,另一种用于绘画。画布放在另一个上面。我使用了两个画布,因为我不希望橡皮擦工具对图像生效。在我的代码中,应用程序绘制的 y 位置并不总是准确的。在大多数情况下,线条绘制得比实际绘制的路径高。
var baseCanvas,baseContext,canvasObj,context;
var lastX,lastY,mouseX,mouseY;
var isMouseDown = false;
var mode = "pen";
$(window).load(function()
{
baseCanvas = document.getElementById("imageCanvas");
baseContext = baseCanvas.getContext("2d");
baseContext.strokeStyle = 'Black';
baseContext.fillStyle = "skyBlue";
baseContext.lineWidth = 5;
baseContext.fillRect(0, 0, baseCanvas.width, baseCanvas.height);
canvasObj = document.getElementById("drawingCanvas");
context = canvasObj.getContext("2d");
context.strokeStyle = 'Black';
context.lineCap = "round";
context.lineJoin = "round";
context.lineWidth = 2;
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - $('#drawingCanvas').offset().left);
mouseY = parseInt(e.clientY - $('#drawingCanvas').offset().top);
lastX = mouseX;
lastY = mouseY;
isMouseDown = true;
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - $('#drawingCanvas').offset().left);
mouseY = parseInt(e.clientY - $('#drawingCanvas').offset().top);
isMouseDown = false;
}
function handleMouseOut(e) {
mouseX = parseInt(e.clientX - $('#drawingCanvas').offset().left);
mouseY = parseInt(e.clientY - $('#drawingCanvas').offset().top);
isMouseDown = false;
}
function handleMouseMove(e) {
mouseX = parseInt(e.clientX - $('#drawingCanvas').offset().left);
mouseY = parseInt(e.clientY - $('#drawingCanvas').offset().top);
if (isMouseDown) {
context.beginPath();
if (mode == 'pen') {
context.globalCompositeOperation = "source-over";
context.moveTo(lastX, lastY);
context.lineTo(mouseX, mouseY);
context.stroke();
} else {
context.globalCompositeOperation = "destination-out";
context.arc(lastX, lastY, 5, 0, Math.PI * 2, false);
context.fill();
}
lastX = mouseX;
lastY = mouseY;
}
}
$(document).on('mousedown',$("#drawingCanvas"),function (e) {
handleMouseDown(e);
});
$(document).on('mousemove',$("#drawingCanvas"),function (e) {
handleMouseMove(e);
});
$(document).on('mouseup',$("#drawingCanvas"),function (e) {
handleMouseUp(e);
});
$(document).on('mouseout',$("#drawingCanvas"),function (e) {
handleMouseOut(e);
});
});
function setCanvas(imageFile)
{
var base_image = new Image();
base_image.src = window.URL.createObjectURL(imageFile[0]);
baseContext.save();
baseContext.clearRect(0, 0, baseCanvas.width, baseCanvas.height);
baseContext.beginPath();
base_image.onload = function()
{
baseContext.drawImage(base_image,0,0, $('#imageCanvas').width(), $('#imageCanvas').height());
baseContext.restore();
}
}