Canvas, write a Sketchpad for fun

I'm sure you've heard about canvas. Today we'll write a simple drawing board with canvas.
First of all, we have to write a canvas label inside the body
//Note: Here we want to give the canvas label a border so that we can see the canvas
 < canvas id = "mycanvas" width = "500" height = "500" style = "border: 1px solid red;" > write the prompt version information here: your browser version is too low, click < a href = "#ාා" > Download < / a > latest version < / Canvas >
The label section is complete. Next is the js part:
Before writing js, analyze the action to be completed -
-When the mouse is pressed, there is a response on the canvas at the beginning, and the position pressed is the starting position of the brush.
-Drag the mouse to get the position of the mouse relative to the element (canvas) is the final position of the brush.
-Mouse up, move the end of the event.
Based on the above analysis, we fill in the corresponding events in turn:
//Get element canvas
var myCanvas = document.getElementById("myCanvas");
//Set the picture book based on 2D deformation
var context  = myCanvas.getContext('2d');
//Press the mouse to get the current position
myCanvas.onmousedown = function(ev){
    //Compatible with IE writing
    var obj = ev || window.event;
    //Mouse down event to get the current position of the mouse inside the element, that is, the starting position of the brush
    var startX = obj .clientX - myCanvas.offsetLeft;
    var startY = obj .clientY - myCanvas.offsetTop;
    ////Create a new path (layer), which must not be omitted here, indicating the beginning of the path. If omitted, no error will be reported, but all things will be drawn on one layer, causing mutual influence
    context.beginPath();
    //Brush start position
    context.moveTo(startX,startY);
    //Move the mouse to get the current position. This must be written in onmousedown event
    myCanvas.onmousemove = function(ev){
        var obj  = ev || window.event;
        //When dragging, get the position of the mouse again. As the end position of the brush, the mouse will drag all the time, and this event will be triggered all the time.
        var endX = obj .clientX - myCanvas.offsetLeft;
        var endY = obj .clientY - myCanvas.offsetTop;
        context.lineTo(endX,endY);
        //Set line color
        context.strokeStyle = "red";
        //Set line width, 5 pixels
        context.lineWidth = 5;
        //
        //Render the figure to the canvas, otherwise, although you have drawn something, it will not be displayed
        context.stroke();
        }
        }
//Mouse up, clear mouse move event
myCanvas.onmouseup = function(){
    myCanvas.onmousemove = null;
}

result:
)

Finally: a very simple small example, to help us understand canvas, hope to help you.

Tags: IE

Posted on Sun, 03 May 2020 08:59:04 -0400 by shaunie123