Html5 javascript canvas library

Canvas API

The Canvas API largely focuses on 2D graphics. The WebGL API, which also uses the element, draws hardware-accelerated 2D and 3D graphics.

Basic example

This simple example draws a green rectangle onto a canvas.

HTML

JavaScript

The Document.getElementById() method gets a reference to the HTML element. Next, the HTMLCanvasElement.getContext() method gets that element’s context—the thing onto which the drawing will be rendered.

The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(10, 10, 150, 100); 

Result

Reference

  • HTMLCanvasElement
  • CanvasRenderingContext2D
  • CanvasGradient
  • CanvasPattern
  • ImageBitmap
  • ImageData
  • TextMetrics
  • OffscreenCanvas
  • Path2D Experimental
  • ImageBitmapRenderingContext Experimental

Note: The interfaces related to the WebGLRenderingContext are referenced under WebGL.

Note: OffscreenCanvas is also available in web workers.

Guides and tutorials

A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.

Читайте также:  Proxy для бота python

A hands-on, book-length introduction to the Canvas API and WebGL.

A handy reference for the Canvas API.

Libraries

The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.

  • EaselJS is an open-source canvas library that makes creating games, generative art, and other highly graphical experiences easy.
  • Fabric.js is an open-source canvas library with SVG parsing capabilities.
  • heatmap.js is an open-source library for creating canvas-based data heat maps.
  • JavaScript InfoVis Toolkit creates interactive data visualizations.
  • Konva.js is a 2D canvas library for desktop and mobile applications.
  • p5.js has a full set of canvas drawing functionality for artists, designers, educators, and beginners.
  • Paper.js is an open-source vector graphics scripting framework that runs on top of the HTML Canvas.
  • Phaser is a fast, free and fun open source framework for Canvas and WebGL powered browser games.
  • Pts.js is a library for creative coding and visualization in canvas and SVG.
  • Rekapi is an animation key-framing API for Canvas.
  • Scrawl-canvas is an open-source JavaScript library for creating and manipulating 2D canvas elements.
  • The ZIM framework provides conveniences, components, and controls for coding creativity on the canvas — includes accessibility and hundreds of colorful tutorials.
  • Sprig is a beginner-friendly, open-source, tile-based game development library that uses Canvas.

Note: See the WebGL API for 2D and 3D libraries that use WebGL.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 19, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Easy canvas — простая js библиотека, которая невероятно упрощает работу с canvas html

Привет всем. Представим, что вы часто работаете с canvas в html. И многие вещи в канвасе делаются не просто. Например чтобы загрузить картинку вам нужно создать объект new Image(), подождать пока прогрузиться, затем только добавить на холст. Или же чтобы нарисовать треугольник вам нужно подбирать координаты и т.п. Очень много строк кода. По этому, если вы потратите 5 минут на изучение данной библиотеки, вы очень сильно сможете упростить отрисовку вашего холста.

Для чего создана это библиотека

Эта очень простая, абсолютно бесплатная, но в то же время сильная библиотека, которая создана специально, чтобы облегчить использование canvas в html. Почему стоит использовать ее вы узнаете ниже, я расскажу вам основные преимущества.

Как подключить

Подключить очень просто, достаточно вписать строчку в ваш html файл

Преимущества

ОЧЕНЬ ПРОСТО НАРИСОВАТЬ ЧТО-ТО

По сути библиотека состоит из объекта new EasyC(). Который имеет два свойства: .canvas и .objects . Первый это DOM элемент канваса, на котором мы будем рисовать. Второй, это массив элементов, которые мы будем рисовать, затем вызываем функцию .draw() и все автоматически рисуется. Например нарисуем картинку:

new EasyC(document.getElementById("canvas"), [< type: "image", x: 250, y: 100, src: "2.png" >]).draw();

И сразу получаете готовое изображение на вашем канвасе.

И даже не нужно создавать объект new Image(), все это библиотека делает сама.

ЛЕГКО ЗАГРУЖАТЬ СТОРОННИЕ ФАЙЛЫ

Как это уже было показано на примере выше с изображением, но также еще очень просто загружать и шрифты, например создадим текст с собственным шрифтом

new EasyC(document.getElementById("canvas"), [< type: "text", x: 250, y: 150, value: "Hello, world\nSecond stroke\nThird stroke", font: "url(myownfont.ttf)", size: 26, align: "left", fill: "#999", >]).draw();

Как вы видите, вы можете даже писать несколько строк разделяя их знаком \n . Еще также покажу на примере как вы можете заполнять фигуры любой картинкой. Тут я не буду писать полностью код, укажу только свойство которое присвоено всем объектам на этом примере.

Первое это ссылка на файл, второе координаты изображение, третье это размеры изображение и четвёртое это указываем будет ли изображение повторяться. Получаем такие фигуры

ВЫ МОЖЕТЕ УКАЗЫВАТЬ Z КООРДИНАТУ

Просто указав z координату вы можете выбирать какой объект будет рисоваться поверх другого. Например

new Easyc(document.getElementById("canvas"), [< type: "triangle", x: 300, y: 105, angleLeft: 1.5*Math.PI/4, angleRight: 1*Math.PI/4, base: 150, fill: "#000", z: 12 >, < type: "rectangle", x: 200, y: 150, width: 100, height: 100, fill: "#999", z: 3 >]).draw();

ВЫ МОЖЕТЕ РАБОТАТЬ С ОТНОСИТЕЛЬНЫМИ КООРДИНАТАМИ

До этого мы все указывали в абсолютных координатах в пикселях, но также вы можете работать с относительными, относительно ширины и высоты канваса. Достаточно установить relative: true

new EasyC(document.getElementById("canvas"), [< type: "rectangle", relative: true, x: 0.5, y: 0.25, width: 0.3, height: 0.3, fill: "#999" >]).draw();

Заключение

Это конечно еще не все свойства, например я не рассказал как создаётся градиент, как делается поворот объектов, прозрачность, масштабирование и т.д. Но основная задача была рассказать о главных преимуществах данной библиотеки. Она очень проста и сильно упрощает вам жизнь. Буду рад, если вам действительно это поможет. Вот, кстати, есть видеоурок, как создаётся мини игра на этой библиотеке.

Источник

My Favorite 5 JavaScript Canvas Libraries – HTML5

html5-canvas

The HTML5 element is used to draw graphics, on the fly, via scripting (usually JavaScript).

The element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.

Here is a sample HTML canvas example:

    Your browser does not support the HTML5 canvas tag.   

Crunchify.com Test

My Favorite JavaScript Canvas Libraries:

1) bHive.js Library:

Create rich user experiences, animations, games and applications with bHive, a HTML 5 canvas framework API built to make developing easier, so you can start creating straight away.

bHive javascript library

2) BitmapDataChannels Library:

HTML5 Canvas API implementation of the AS3 BitmapData class.

BitmapDataChannels javascript library

3) Paper.js Library:

Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas. It offers a clean Scene Graph / Document Object Model and a lot of powerful functionality to create and work with vector graphics and bezier curves, all neatly wrapped up in a well designed, consistent and clean programming interface.

paper.js javascript library

4) HTML Canvas Library:

HTML canvas library is a full-featured lightweight wrapper library of the native html canvas element written in Javascript, aimed to make visualization and animation using canvas simpler. Features animation support, layers, event capture, multitouch and many examples.

HTML Canvas javascript library

5) Fabric.js Library:

Fabric.js is a powerful and simple Javascript canvas library. Fabric provides interactive object model on top of canvas element. Fabric also has SVG-to-canvas (and canvas-to-SVG) parser.

Febric.js javascript library

Which one is your favorite one? Let us know in comment section below.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

Оцените статью