Canvas
Canvas is a special API component in ElenixOS for drawing graphics and images. This document will introduce the features, usage methods, and precautions of the canvas component.
Feature Introduction
The canvas component allows developers to draw various graphics and images on it, such as lines, rectangles, circles, text, etc. Canvas components are typically used for creating custom graphics, charts, games, and other scenarios.
Usage Methods
Create Canvas
Use the new lv.canvas() constructor to create a canvas object:
// Create canvas object
const canvas = new lv.canvas(eos.view.active());
Configure Canvas
Use the following methods to configure the canvas:
// Set canvas size
canvas.setSize(200, 200);
// Set canvas position
canvas.setPos(10, 10);
// Get canvas buffer
const buf = canvas.getBuffer();
// Create drawing context
const ctx = canvas.getContext("2d");
Draw Graphics
Use the drawing context to draw various graphics:
// Draw line
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(190, 190);
ctx.stroke();
// Draw rectangle
ctx.fillStyle = "#FF0000";
ctx.fillRect(50, 50, 100, 100);
// Draw circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = "#00FF00";
ctx.fill();
// Draw text
ctx.font = "20px Arial";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.fillText("Hello", 100, 100);
// Refresh canvas
canvas.refresh();
Example: Create a Simple Canvas
// Create canvas
const canvas = new lv.canvas(eos.view.active());
canvas.setSize(200, 200);
canvas.align(lv.ALIGN_CENTER, 0, 0);
// Get drawing context
const ctx = canvas.getContext("2d");
// Draw graphics
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(190, 190);
ctx.stroke();
ctx.fillStyle = "#FF0000";
ctx.fillRect(50, 50, 100, 100);
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = "#00FF00";
ctx.fill();
// Refresh canvas
canvas.refresh();
Example: Create a Dynamic Canvas
// Create canvas
const canvas = new lv.canvas(eos.view.active());
canvas.setSize(200, 200);
canvas.align(lv.ALIGN_CENTER, 0, 0);
// Get drawing context
const ctx = canvas.getContext("2d");
// Dynamic drawing
let angle = 0;
setInterval(() => {
// Clear canvas
ctx.clearRect(0, 0, 200, 200);
// Draw rotating rectangle
ctx.save();
ctx.translate(100, 100);
ctx.rotate(angle);
ctx.fillStyle = "#FF0000";
ctx.fillRect(-50, -50, 100, 100);
ctx.restore();
// Refresh canvas
canvas.refresh();
// Update angle
angle += 0.1;
}, 50);