画布在不同尺寸下表现异常 [英] Canvas behaves oddly at different sizes
问题描述
最近开始玩画布,但是在不同的尺寸下表现却很奇怪。
Been playing around with canvas lately, but it behaves oddly at different sizes.
这是我的代码:
HTML:< canvas>< / canvas>
CSS: canvas {width:300px;高度:50px; }
JS:
var c = document.querySelector("canvas"),
ctx = c.getContext("2d");
ctx.fillRect(10,10,50,50); // fill a 50x50 square at pos (10,10)
在画布尺寸300x50处,以下内容是绘制:
At canvas size 300x50, the following is drawn:
在画布尺寸为100x200的情况下,绘制以下内容:
At canvas size 100x200, the following is drawn:
很明显,一个像素实际上并不意味着一个像素-我做错了吗?
It's clear that one pixel does not actually mean one pixel - am I doing something wrong?
推荐答案
请勿使用CSS更改画布的大小。而是更改元素的大小:
Don't use CSS to change the size of the canvas. Instead change the size of the element:
c.width=300;
c.height=50;
这是因为当您使用CSS调整尺寸时,您是在拉伸像素。更改元素本身的大小时,实际上是在添加/减去像素。
That's because when you resize with CSS you're "stretching" the pixels. When you change the size of the element itself, you are actually adding/subtracting pixels.
这篇关于画布在不同尺寸下表现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!