mousedown
で始まり、mouseup
で終了する行を描画することが目的です。その間に、draw()
ファンクションを使用してキャンバスに線を描画し、mousemouse
の間に線を描画します。私は線が引っ張られている間キャンバスをクリアする必要があります。関数内のHTML5キャンバス参照
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:
ReferenceError: canvas is not defined
at HTMLCanvasElement.InitThis.c.onmousemove (zivuqeyure.js:22:31)
がどのように私は関数内のキャンバスを参照することができます。
<!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>
私はこのエラーを取得しますか?
'ctx.clearRect(0、0、canvas.width、canvas.height);'では、定義されていない 'canvas'を参照しています。 – Cerbrus
'' canvas '!==' c'' – ndugger
@nduggerあなたはどういう意味ですか? – alkopop79