目的是能够以mousedown
开头并使用mouseup
完成一条线。在两者之间,在mousemouse
时,用draw()
功能将线条绘制到画布上。我需要在拖动线时清除画布。
JS:
var c = document.getElementById("canvas1");
var ctx = c.getContext("2d");
var isDrawing = false;
var mX, mY, rX, rY;
function InitThis() {
c.onmousedown = function(e) {
isDrawing = true;
mX = e.clientX;
mY = e.clientY;
};
c.onmousemove = function(e) {
if (isDrawing) {
rX = e.clientX;
rY = e.clientY;
draw();
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
};
c.onmouseup = function(e) {
rX = e.clientX;
rY = e.clientY;
isDrawing = false;
}
}
function draw() {
ctx.beginPath();
ctx.moveTo(mX,mY);
ctx.lineTo(rX, rY);
ctx.closePath();
ctx.stroke();
}
InitThis()
html:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[draw lines with mouse]">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas id="canvas1" width="800" height="900" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</body>
</html>
我得到此错误:
ReferenceError: canvas is not defined
at HTMLCanvasElement.InitThis.c.onmousemove (zivuqeyure.js:22:31)
如何在功能中引用画布?
您正在用变量" c"引用一个帆布对象。
这是代码的第一行。
稍后,您尝试参考未定义的"画布"变量。(您应该使用" C"代替"帆布")
解释器不知道"画布"是指"存储在c中的帆布对象"。解释器确实可以按照您的要求进行操作,但是您尝试指的是不存在的变量。