Aufgabenstellung
In einem HTML 5 Canvas soll über JavaScript-Events die Mausposition ausgelesen, und an dieser gemalt werden.
Ansatz
Verwendung der Events onmousedown, onmouseup, onmousemove des Canvas-Elements. Nutzung der clientX- und clientY-Eigenschaft
Prämissen / Vorraussetzungen
Es wird ein aktueller Browser verwendet, der das HTML 5 Canvas-Element unterstützt.
Lösung
<html> <head> <script> function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "black"; ctx.beginPath(); var x; var y; canvas.onmousedown = function(e) { x = e.clientX; y = e.clientY; ctx.moveTo(x, y); } canvas.onmouseup = function(e) { x = null; y = null; } canvas.onmousemove = function(e) { if (x == null || y == null) { return; } x = e.clientX; y = e.clientY; x -= canvas.offsetLeft; y -= canvas.offsetTop; ctx.lineTo(x, y); ctx.stroke(); ctx.moveTo(x, y); } }; </script> </head> <body onload="draw();"> <canvas id="canvas" width="300" height="300" style="border: 1px solid black;"></canvas> </body> </html>
Hi,
cooles Skript. Direkt ausprobiert und funktioniert fast einwandfrei.
Hast du eine Idee, weshalb der Browser immer einen seitwärts Strich zeichnet, bevor er die Bewegung zeichnet?
VG Martin
canvas.onmousedown = function(e) {
x = e.clientX;
y = e.clientY;
ctx.moveTo(x – canvas.offsetLeft, y – canvas.offsetTop);
}