简体   繁体   中英

HTML5 canvas perform inconsistent when define its width and height using ID selector

My html file is very simple:

<body>
<canvas id="canvas" width="900" height="400"></canvas>
<button onclick="DrawSVG()">Draw SVG</button>
</body>

When click the button I draw the SVG on the canvas, using canvg.js

var opts = {
  ignoreMouse: false,
  ignoreClear: true,
  ignoreDimensions : true,
  offsetX: 0,
  offsetY: 0
};
canvg(canvas, "face.svg", opts);

face.svg:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" >
<rect x="0" y="0" width="80" height="80" rx="6" fill="blue" stroke="red" stroke-
width="1px" fill-opacity="0.7" />
</svg>

It seems correct.

But when I define the width and height in the head:

<style type="text/css">
#canvas {
width: 900px;
height: 400px;
}

The svg on the canvas is 4 times larger than before. What's the difference?

The explanation is here: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

(I borrowed this from here! because it's worth repeating.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM