圆角矩形方法将不同的结果返回到常规的fillrect方法-canvas

时间:2019-08-06 16:31:06

标签: javascript

我有一个相当简单的脚本,该脚本将值数组中的样本呈现到Canvas上。在我尝试制作脚本之前,脚本一直运行良好,以使每个渲染的示例均取整而不是正方形。此数组的示例为[49, 128, 140, 139, 140 ...](最大值和最小值始终分别为1400)。


代码

我使用了this答案的修改版本来实现它:

CanvasRenderingContext2D.prototype.roundedRect = function(options){
    if(options.width && options.height && options.top && options.left){
        var x = options.left, y = options.top,
            width = options.width, height = options.height;

        var fill = options.fill || true,
            stroke = options.stroke || false,
            radius = options.radius || (width / 2);

        if(height < 2) radius = 0;
        if(typeof radius === "number"){
            radius = { tl: radius, tr: radius, br: radius, bl: radius };
        } else {
            var radiux = { tl: 0, tr: 0, br: 0, bl: 0 };
            for(var side in radiux){
                radius[side] = radius[side] || radiux[side];
            }
        }

        this.beginPath();

        this.moveTo(x + radius.tl, y);
        this.lineTo(x + width - radius.tr, y);

        this.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
        this.lineTo(x + width, y + height - radius.br);

        this.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
        this.lineTo(x + radius.bl, y + height);

        this.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
        this.lineTo(x, y + radius.tl);

        this.quadraticCurveTo(x, y, x + radius.tl, y);

        this.closePath();
    }
}

这是我如何实现的示例:

var sampleWidth = 3;
var samples = [ ... ], 
    samplesLength = samples.length,
    adjustedLength = canvasWidth / (sampleWidth + 1);

var x = 0;
for(var i = 0; i < adjustedLength; i++){
    var sampleIndex = Math.floor(i * (samplesLength + Math.floor(samplesLength / adjustedLength)) / adjustedLength),
        leftIndex = samples[sampleIndex - 1] ? samples[sampleIndex - 1] : samples[sampleIndex],
        rightIndex = samples[sampleIndex + 1] ? samples[sampleIndex + 1] : samples[sampleIndex];

    var height = ((leftIndex + samples[sampleIndex] + rightIndex) / 3) * (canvasHeight / 140);
        height = height < 1 ? 1 : height;

    // the same can be done with fillRect if
    // simply swap out the method name and rearrange the values to their correct positions
    context.fillStyle = color;
    context.roundedRect({
        top: canvasHeight - height,
        left: x + (x * sampleWidth),
        width: sampleWidth,
        height: height,
        radius: 2
    });
    context.fill();

    x++;
}

问题

使用roundedRect代替fillRect方法时,由于某种原因(通常似乎是一个样本的值为140),它只会输出空白-这很奇怪,因为当我在绘图脚本或console原型中height roundedRect时,它们会始终输出正确和期望的值;因此没有理由出现随机空虚

使用fillRectfillRect
使用roundedRectroundedRect

(请注意,最有可能是140的那些是尚未渲染的)

0 个答案:

没有答案