My Canvas common methods and requestAnimationFrame

My favorite canvas function

  • Get target element

    var myCanvas = document.getElementById("canvas");
    var context = myCanvas.getContext("2d");
  • draw rectangle

    context.fillRect(x, y, width, height); // Draw a solid rectangle
    context.strokeRect(x, y, width, height); // Draw a white rectangle
  • Draw path

    context.beginPath(); // Start drawing path
    context.moveTo(x, y); // Path start coordinates
    context.lineTo(x, y); // Path end point coordinates
    context.stroke(); // Draw a void path
    context.fill(); // Draw a solid path
    context.closePath(); // End of drawing path
  • Draw text

    context.font = "60px Blackbody"; // Font information, at least including font size and font name
    context.fillText(text, x, y); // Draw solid text
    context.strokeText(text, x, y); // Draw white text
  • Draw style

    context.fillStyle = "red"; // Solid color
    context.strokeStyle = "#ff4355"; // Hollow color
    context.lineWidth = 32; // 
  • Draw other

    context.arc(x, y, r, startAngle, endAngle, false);
    // Draw the circle x,y as the center coordinate, r as the radius of the circle, sA as the start radian of the circle, eA as the end of the circle
    // Radian, false means drawing in clockwise direction, and true means anticlockwise.  
    // For example, a circle is:  
    context.arc(100, 100, 100, 0, 2*Math.PI, false);
    context.drawImage(image, x, y, width, height);
    // Pass in a picture instance and draw it on the canvas
    context.drawImage(image, sx, sy, sw, sh, x, y, width, height);
    // Clip the picture
    context.clearRect(x, y, width, heigth); // Clear canvas


    What does he do? In the early browser, we used setTimeOut and setInterval to implement animation, but we know JS is single thread, tasks in setTimeOut and setInterval will be saved in asynchronous queue, and will be loaded and executed only after the tasks in synchronous queue are completed, so if tasks in asynchronous queue are very slow to execute, tasks in asynchronous queue can only be executed Waiting. But if it does, it's going to get stuck, and it's a bad experience.
    The emergence of request animation frame is to solve this problem. It is an API specially designed to achieve high-performance frame animation, rendering animation with the efficiency of 60 frames per second. Currently, it has been supported in many browsers. You can use it in DOM effect switching or Canvas animation.
    The compatible methods in multiple browsers are as follows:

    window.requestAnimaFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
    window.setTimeout(callback, 1000 / 30);

Examples are as follows

Tags: Javascript

Posted on Sun, 03 May 2020 08:54:08 -0400 by Domcsore