Как canvas сделать фоном

от admin

Как canvas сделать фоном

Вместо конкретного цвета для заливки фигур, например, прямоугольников, мы можем использовать изображения. Для этого у кконтекста canvas имеется функция createPattern() , которая принимает два параметра: изображение, которое будет использоваться в качестве фона, и принцип повторения изображения. Последний параметр играет роль в том случае, если размер изображения у нас меньше, чем размер фигуры на canvas. Этот параметр может принимать следующие значения:

repeat : изображение повторяется для заполнения всего пространства фигуры

repeat-x : изображение повторяется только по горизонтали

repeat-y : изображение повторяется только по вертикали

no-repeat : изображение не повторяется

Нарисуем прямоугольник и выведем в нем изображение:

Чтобы использовать изображение, нам надо создать элемент Image и установить источник изображения — локальный файл или ресурс в сети:

HTML Canvas API Tutorial

The HTML canvas is an HTML tag, <canvas> , which is an element where we can draw to using the Canvas API.

Create a canvas

Creating a canvas is as simple as dropping a <canvas></canvas> in a blank HTML file:

You don’t see anything in the page because the canvas is an invisible element. Let’s add some border:

Chrome automatically adds an 8px margin to the body element. This is why our border looks like a frame, and you can remove that margin by setting

We’ll leave the default for now.

Our canvas is now reachable from JavaScript using the DOM Selectors API, so we can use document.querySelector() :

Change the background color of a canvas

You do that in CSS:

Resize a canvas

You can set the width and height in CSS:

and in this way the canvas will expand to fill all the outer element size.

If you put the canvas as a first level element in the HTML, the above code will expand the canvas to fit the entire body.

The body is not filling the entire window size. To fill the entire page instead we need to use JavaScript:

If you now remove the body margin and set the background of the canvas using CSS, we can fill our entire page with the canvas and we can start drawing on it:

If the window resizes we need to recalculate the canvas width as well, using a debounce to avoid calling too many times our canvas resizing (the resize event can be called hundreds of times as you move the window with the mouse, for example):

Get a context from the canvas

We want to draw to the canvas.

To do this, we need to get a context:

Some assign the context to a variable named c , some ctx — it’s a common way to shortcut “context”

The getContext() method returns a drawing context on the canvas, according to the type that you pass as parameter.

Valid values are

  • 2d , the one we’ll use
  • webgl to use WebGL version 1
  • webgl2 to use WebGL version 2
  • bitmaprenderer to use with ImageBitmap

Based on the context type, you can pass a second parameter to getContext() to specify additional options.

In the case of the 2d context, we basically have one parameter we can use in all browsers, and it’s alpha , a boolean that defaults to true. If set to false, the browser knows the canvas does not have a transparent background and can speed up rendering.

Draw elements to a canvas

With the context we can now draw elements.

We have several methods to do so. We can draw:

  • text
  • lines
  • rectangles
  • paths
  • images

and for each of those elements we can alter the fill, the stroke, the gradient, the pattern, the shadow, rotate them, scale and perform a lot of operations.

Let’s start with the simplest thing: a rectangle.

The fillRect(x, y, width, height) method serves this purpose:

This is going to draw a black rectangle of 100 x 100 pixels, starting from position x 100 and y 100:

You can color the rectangle by using the fillStyle() method, passing any valid CSS color string:

You can get creative now and draw many things in this way:

Drawing elements

As mentioned you can draw many things:

  • text
  • lines
  • rectangles
  • paths
  • images

Let’s just see a few of them, rectangles and text, to get the gist of how things work. You can find the API for all the rest that you need here.

Changing the colors

Use the fillStyle and strokeStyle properties to change the fill and stroke colors of any figure. They accept any valid CSS color, including strings and RGB calculations:

Rectangles

You have 3 methods:

  • clearRect(x, y, width, height)
  • fillRect(x, y, width, height)
  • strokeRect(x, y, width, height)

We saw fillRect() in the previous section. strokeRect() is similar in how it’s called, but instead of filling a rect, it just draws the stroke using the current stroke style (which can be changed using the strokeStyle context property):

clearRect() sets an area as transparent:

Drawing text is similar to rectangles. You have 2 methods

  • fillText(text, x, y)
  • strokeText(text, x, y)
Читать:
Три человека обменялись рукопожатиями сколько было рукопожатий ответ

which let you write text on the canvas.

x and y refer to the bottom-left corner.

You change the font family and size using the font property of the canvas:

There are other properties you can change, related to text (* = default):

  • textAlign (start*, end, left, right, center)
  • textBaseline (top, hanging, middle, alphabetic*, ideographic, bottom)
  • direction (ltr, rtl, inherit*)

Lines

To draw a line you first call the beginPath() method, then you provide a starting point with moveTo(x, y) , and then you call lineTo(x, y) to make the line to that new coordinates set. You finally call stroke() :

The line is going to be colored according to the c.strokeStyle property value.

A more complex example

This code creates a canvas that generates 800 circles:

Every circle is perfectly contained in the canvas, and its radius is randomized.

Any time you resize the window, the elements are regenerated.

You can play around with on Codepen.

Another example: animating elements on the canvas

Based on the example above, we animate the elements using a loop. Every circle has its own “life” and moves within the borders of the canvas. When the border is reached it bounces back:

We achieve this by using requestAnimationFrame() and slightly moving the image at every frame rendering iteration.

Interact with the elements on the canvas

Here is the above example expanded to let you interact with the circles using the mouse.

When you hover the canvas, the items near your mouse will increase in size, and they will return back to normal when you move somewhere else:

How does it work? Well, first I track the mouse position using 2 variables:

Then we use those variables inside the update() method of Circle, to determine if the radius should increase (or decrease):

distanceFromMouse is a value expressed in pixels (set to 200) that defines how far we want the circles to react to the mouse.

Performance

If you try to edit those projects above and add a bunch more circles and moving parts, you’ll probably notice performance issues. Browsers consume a lot of energy to render the canvas with animations and interactions, so pay attention so that the experience is not ruined on less performant machines than yours.

In particular I had issues when trying to create a similar experience with emojis rather than circles, and I found that text takes a lot more power to render, and so it was sluggish pretty quickly.

This page on MDN lists many performance tips.

Closing words

This was just an introduction to the possibilities of Canvas, an amazing tool that you can use to create incredible experiences on your web pages.

Как сделать canvas в качестве фона для div?

Всем привет.
Есть обычный канвас, в который вставлена картинка.
Пытаюсь этот канвас добавить в качестве фона для div.

В инспекторе вижу, что путь к канвосу добавляется, но ничего не рисует, подскажите пожалуйста, в чем проблема?

  • Вопрос задан более трёх лет назад
  • 1300 просмотров
  • Facebook
  • Вконтакте
  • Twitter

UnluckySerivelha

  • Facebook
  • Вконтакте
  • Twitter

HellishCode

HellishCode

sfi0zy

Проверьте правильность позиционирования этого фона, может он у вас съехал куда-то и вы его не видите. Плюс не забывайте, что у png есть прозрачность, и, если канвас закрашен не полностью, а вы используете лишь его часть, то сложится впечатление, что на фоне ничего нет, хотя там что-то есть.

Use <canvas> as a CSS background

This has been possible in WebKit since 2008, see here.

Currently, Firefox 4 contains a feature, which allows you to use any element (including canvas) as a CSS background, in this fashion:

atiquratik's user avatar

Yes. You can put a canvas in CSS background.

I know this is a pretty old question but I felt like posting my answer for people who’d visit this page because this is the correct answer, in just one line of code, using the .toDataURL function. It works in every browser that supports canvas.

frenchie's user avatar

I think the closest you could get is to render into a canvas , call toDataUrl() on it to retrieve the contents as an image, and assignment that result to the desired element’s background-image property. This will only give a static background, though. If you want to be able to further update the canvas , however, then you’ll need to instead position the canvas behind another element, as Johan has already suggested.

I’ve been triying to achieve this same feature past weeks, the best solution I’ve found its the same proposed by bcat:

  1. Render canvas (visible or hidden)
  2. Get canvas image with «canvas.toDataURL»
  3. Asign this image-data as background image for the element (I use MooTools)

The bad news, for static images works great, but with animation in Chrome sometimes «blinks», and in Firefox blinks-a-lot. Maybe someone knows a workaround to get rid of this «nasty blinking».

Похожие статьи