create paint in javascript

To create a paint using Javascript, one can use the HTML5 <canvas> element. Here is an example:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="500" height="500"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var isPainting = false;

canvas.addEventListener("mousedown", function(event){
    isPainting = true;
    context.beginPath();
    context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
});

canvas.addEventListener("mousemove", function(event){
    if (isPainting) {
        context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
        context.stroke();
    }
})

canvas.addEventListener("mouseup", function(event){
    isPainting = false;
});

</script>

</body>
</html>
722 chars
34 lines

This code creates a canvas element with id myCanvas and size of 500x500. It also creates a Javascript context for the canvas, which is used to draw on the canvas.

We then add event listeners to the canvas for mousedown, mousemove, and mouseup. When the user presses down on the mouse button, we set a flag isPainting to true and start a new path with context.beginPath(). We also move the cursor to the current mouse position with context.moveTo(). When the user moves the mouse, we draw a line from the previous point to the current mouse position with context.lineTo() and then call context.stroke() to actually draw the line. Finally, when the user lifts the mouse button, we set isPainting to false.

gistlibby LogSnag