以下は、ユーザーがキャンバスに描画できるようにするコードです。これは問題なく動作します。私が問題を抱えている部分は、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;
}
}