primers

When I met the need of composite pictures in my recent work, the first thing that came to my mind was canvas. I searched some materials on the Internet, and most of them also used canvas. Because for a long time did not actually contact with this aspect of things, feel some excitement. I’m expecting a lot.

Wide high problem

Since it is on a mobile phone, different sizes need to be adapted. Rem units are used in the project, considering that the global properties width and height should be supported in theory. The following attempts were made.

HTML tag attribute Settings

Here is an example, scan the QR code for access below.

I found that this idea was wrong, but when I looked at the description in the specification, I found that it was very clear:

The canvas element has two attributes to control the size of the element’s bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

The Canvas element has two properties that control the bitmap of elements: width and height. These attributes, when specified, must be non-negative integer values. Be sure to use the same rules for parsing non-negative integers to get their numeric values. If an attribute value does not exist, or if parsing returns an error, always use the default value. The default value for the width attribute is 300, and the default value for the height attribute is 150.

If you look closely and put it into practice, you’ll see that the width and height attributes with units on an HTML tag don’t work.

CSS Properties

In addition to setting element attributes directly, you can also control the width and height of the canvas using CSS. Here is an example, scan the QR code for access below.

Practice turns out it can. In addition, you can see from the example:

  1. Width and height properties are not set on the canvas tag, and only one of them is set with CSS. Then the value of the other property will be converted according to the default width to height ratio: 300:150 = 2:1.
  2. If CSS is used to set only one of the properties width and height, the value of the other property will be converted according to the ratio of width and height on the canvas tag.

In this way, the overall display can be adaptive.

Dynamic calculation

According to the ratio of width to height using JS dynamic calculation after the assignment, can also achieve a display of self-adaptive effect.

The above method is only the overall display, and there will be other problems in practical application, which will be explained in more detail in canvas display ambiguity.

The resources

  • The canvas element