Offsetwidth of the canvas element

Time:2021-6-29

A project in progress uses canvas. According to the style and size of canvas elements, window. Devicepixelratio
Dynamically set the width and height of the canvas element.

However, it is found that the offset width of canvas element seems to be the CSS footprint size multiplied by window. Devicepixelratio.
The code is as follows:

<div class="canvas-container">
  <canvas></canvas>
</div>
<div id="text"></div>
body {
    margin: 0;
}
.canvas-container {
  width: 500px;
  height: 500px;
  margin: 100px auto;
  background: rgba(0, 0, 0, 0.3);
}
canvas {
    display: block;
    height: 100%;
}
document.querySelector('#text').innerHTML = document.querySelector('.canvas-container').offsetWidth + ' ' + document.querySelector('canvas').offsetWidth;

MBP is used for development. This computer is retina screen, and window.devicepixelratio is 2,
It is found that in chrome and safari, 500 and 1000 are displayed

Wait for the project to go online, and then go back to study this issue in detail.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]