I need to be able to draw in a canvas using JavaScript.
I have the following code:
.JS
function CursorSign() {
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var isDrawing = false;
var lastX, lastY;
ctx.strokeStyle = "#000000";
ctx.lineWidth = 2;
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", stopDrawing);
function startDrawing(e) {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
}
function draw(e) {
if (!isDrawing) return;
var x = e.offsetX;
var y = e.offsetY;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
lastX = x;
lastY = y;
}
function stopDrawing() {
isDrawing = false;
var imageData = canvas.toDataURL();
var base64Data = imageData.replace(/^data:image/(png|jpeg);base64,/, '');
document.getElementById('<%= HiddenField1.ClientID %>').value = base64Data;
}
}
.ASPX
<table border="1" cellpadding="0">
<tr>
<td>
<canvas id="mycanvas" name="cnv"></canvas>
</td>
</tr>
</table>
With the mouse cursor it works fine. But on mobile, like a tablet or a phone, it just moves the page around.
It also doesn’t work on chrome’s mobile version on the inspection console.
What other approach can I use?