下面是允许用户绘制到画布的代码。这很好用,我有问题的部分是用javascript选择不同的颜色,所以用户有更多的颜色选择
这是绘图部分的代码
window.addEventListener("load", canvasAnimate, false);
function canvasAnimate() {
var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
window.addEventListener('mousemove', MouseIsMoving, false);
window.addEventListener('mousedown', sketchit, false);
window.addEventListener('mouseup', dontDraw, false);
};
// GLOBAL VARIABLES
var mouseX;
var mouseY;
var MouseIsDown = false // this will be used to determine if the mouse is down or not
// e means the event, this stores the mouse events in the variable mouseX and mouseY
function MouseIsMoving(e) {
mouseX = e.pageX - canvas.offsetLeft; //the offset makes the coordinates fit for the canvas box
mouseY = e.pageY - canvas.offsetTop;
document.getElementById('mouseCoordinates').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;
if (MouseIsDown) {
context.lineTo(mouseX, mouseY);
context.stroke();
}
}
function sketchit(e) {
context.beginPath()
context.moveTo(mouseX, mouseY);
context.lineTo(mouseX,mouseY)
context.lineCap = 'round'; //default lineCap and lineWidth
context.lineWidth = 3;
context.strokeStyle = '#000000' //default color
context.stroke();
MouseIsDown = true;
};
function dontDraw() {
if (MouseIsDown) {
MouseIsDown = false;
}
}