Canvas

Extends Composite

Canvas is a widget that can be used to draw graphics using a canvas context.

Import this type with “const {Canvas} = require('tabris');

Canvas on Android

Example:

  1. new Canvas({
  2. left: 0, top: 0, right: 0, bottom: 0
  3. }).on("resize", ({target: canvas, width, height}) => {
  4. let ctx = canvas.getContext("2d", width, height);
  5. ctx.moveTo(0, 0);
  6. // ...
  7. }).appendTo(page);

Methods

getContext(contextType, width, height)

Parameters:

  • contextType: string
    • the context identifier. Only "2d" is currently supported.
  • width: number
    • the width of the canvas context to create
  • height: number

Returns the drawing context with the given size.

Example

  1. const {Canvas, ui, device} = require('tabris');
  2. // Draw shapes on a canvas using HTML5 Canvas API
  3. new Canvas({
  4. left: 10, top: 10, right: 10, bottom: 10
  5. }).on('resize', ({target: canvas, width, height}) => {
  6. let scaleFactor = device.scaleFactor;
  7. let ctx = canvas.getContext('2d', width * scaleFactor, height * scaleFactor);
  8. ctx.scale(scaleFactor, scaleFactor);
  9. ctx.strokeStyle = 'rgb(78, 154, 217)';
  10. ctx.lineWidth = 10;
  11. ctx.moveTo(20, 20);
  12. ctx.lineTo(width - 40, height - 40);
  13. ctx.stroke();
  14. // draw image
  15. ctx.putImageData(createImageData(80, 40), 100, 100);
  16. // copy region
  17. let data = ctx.getImageData(0, 0, 100, 100);
  18. ctx.putImageData(data, 180, 100);
  19. }).appendTo(ui.contentView);
  20. function createImageData(width, height) {
  21. let array = [];
  22. for (let y = 0; y < height; y++) {
  23. for (let x = 0; x < width; x++) {
  24. let alpha = x % 20 > y % 20 ? 255 : 0;
  25. array.push(200, 0, 0, alpha);
  26. }
  27. }
  28. return new ImageData(new Uint8ClampedArray(array), width, height);
  29. }

See also

原文:

https://youjingyu.github.io/Tabris-Documention/?folderName=widgets&pageName=Canvas.html