我看了看并找到了问题所在。在你们的第 19 行Paint.js
有这个:
var ctxCursor = canvasBg.getContext('2d');
这实际上应该是:
var ctxCursor = canvasCursor.getContext('2d');
还有其他一些问题,所以我清理了它们,现在它工作得很好:http: //jsfiddle.net/VmvqJ/2/
这是你的新Paint.js
脚本:
//////////////////// Wayne Daly
/////////////////// 03/06/2013
$(document).ready(function () {
/////////////// SETTING UP CONTEXT & VARIABLES ///////////////
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
canvasWidth = canvas.width,
canvasHeight = canvas.height;
var canvasCursor = document.getElementById('canvasCursor'),
ctxCursor = canvasCursor.getContext('2d');
var mouseX,
mouseY,
clickX = [],
clickY = [],
clickDrag = [],
paint = false,
brushSize = 20;
/////////////// EVENT HANDLERS ///////////////
$('#canvasCursor').mousemove(function (e) {
updateCursor(this, e);
console.log(paint);
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvasCursor').mousedown(function (e) {
console.log('down');
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvasCursor').mouseup(function (e) {
console.log('up');
paint = false;
});
/////////////// GENERAL FUNCTIONS ///////////////
function updateCursor(elem, e) {
ctxCursor.clearRect(0, 0, canvasWidth, canvasHeight);
mouseX = e.pageX - elem.offsetLeft;
mouseY = e.pageY - elem.offsetTop;
ctxCursor.beginPath();
ctxCursor.arc(mouseX, mouseY, brushSize, 0, 2 * Math.PI, false);
ctxCursor.fillStyle = 'green';
ctxCursor.fill();
}
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function Paint(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
ctx.beginPath();
ctx.arc(mouseX, mouseY, brushSize, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
}
function redraw() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Clears the canvas
ctx.strokeStyle = "#df4b26";
ctx.lineJoin = "round";
ctx.lineWidth = 5;
for (var i = 0; i < clickX.length; i++) {
ctx.beginPath();
if (clickDrag[i] && i) {
ctx.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
ctx.moveTo(clickX[i] - 1, clickY[i]);
}
ctx.lineTo(clickX[i], clickY[i]);
ctx.closePath();
ctx.stroke();
}
}
});
并将其添加到您的页面<head>
标签之间:
<style type="text/css">
body {
background:#303030;
}
#canvas, #canvasCursor {
cursor: none;
background: #fff;
position: absolute;
left: 50px;
top: 30px;
z-index: 1;
}
#canvasCursor {
z-index: 20;
background: none;
}
</style>
然后用这个替换你的<body>
标签和里面的所有东西:
<body>
<canvas id="canvasCursor" width="1000px" height="600px"></canvas>
<canvas id="canvas" width="1000px" height="600px"></canvas>
</body>