假设我有以下HTML:
<div>
<canvas class="colorPicker" width="800" height="800"></canvas>
<canvas class="colorPicker" width="800" height="800"></canvas>
</div>
而且,这个CSS:
div {
display: flex;
width: 100%;
overflow: hidden;
}
div > canvas{
flex-grow: 1;
flex-shrink: 1;
width: 50%;
}
画布不按比例缩放。它们比它们宽。当我在画布上绘制圆圈时,这是可见的。
(JSFiddle:https://jsfiddle.net/08rckfek/)
为什么会这样?
如果我不在父div中使用flexbox,则会正确缩放画布。
此外,我必须指定width: 50%
似乎很奇怪。即使我指定基础,也会忽略flex-shrink
。
如何根据父Flexbox的宽度制作一排自动按比例缩放的画布?
答案 0 :(得分:1)
您需要将align-items
设置为默认值stretch
document.addEventListener('DOMContentLoaded', (e) => {
document.querySelectorAll('canvas.colorPicker').forEach((canvas) => {
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(canvas.width, canvas.height) / 2;
// Base white circle, so middle has a full color
ctx.beginPath();
ctx.arc(centerX, centerY, radius/2, 0, 2*Math.PI, false);
ctx.closePath();
ctx.fillStyle = '#fff';
ctx.fill();
for (let angle=0; angle<=360; angle+=1) {
const startAngle = (angle-2)*Math.PI/180;
const endAngle = angle * Math.PI/180;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
gradient.addColorStop(0, 'hsl(' + angle + ', 100%, 100%)');
gradient.addColorStop(0.5, 'hsl(' + angle + ', 100%, 50%)');
gradient.addColorStop(1, 'hsl(' + angle + ', 100%, 0%)');
ctx.fillStyle = gradient;
ctx.fill();
}
});
});
div {
display: flex;
width: 100%;
overflow: hidden;
align-items:flex-start;
}
div > canvas{
flex-grow: 1;
flex-shrink: 1;
width: 50%;
}
<div>
<canvas class="colorPicker" width="800" height="800"></canvas>
<canvas class="colorPicker" width="800" height="800"></canvas>
</div>