如何在JavaScript中调整画布的webgl上下文大小?

时间:2018-09-18 11:40:57

标签: javascript webgl mapbox

首先,感谢您阅读我的问题,并尝试帮助我并为我的英语道歉。

我正在尝试使用您作为参数传递的dpi调整画布的大小。 我正在使用图层类型矢量,因此canvas.getContext("2d") return null正在使用canvas.getContext('webgl')

setDPI(canvas, dpi) {
    var scaleFactor = dpi / 96;
    canvas.width = Math.ceil(canvas.width * scaleFactor);
    canvas.height = Math.ceil(canvas.height * scaleFactor);
    var ctx = canvas.getContext("2d");
    ctx.scale(scaleFactor, scaleFactor);
};

所以这段代码会崩溃,因为canvas.getContext(“ 2d”)返回null;

如何使用webgl调整画布大小?

这是我的代码:

handleFinish = (e) => {
    e.preventDefault();
    let canvas = this.props.map.getCanvas();
    let gl = canvas.getContext('webgl');
    this.resize(gl);
    console.log('canvas1: ', canvas);
    var dims = {
        'A0': [1189, 841],
        'A1': [841, 594],
        'A2': [594, 420],
        'A3': [420, 297],
        'A4': [297, 210],
        'A5': [210, 148]
    };

    var dim = dims[this.state.paper];
    var pageWidth, pageHeight;
    if (this.state.orientation === 'portrait') {
        pageWidth = dim[1];
        pageHeight = dim[0];
    } else {
        pageWidth = dim[0];
        pageHeight = dim[1];
    }
    var ratio = canvas.width/canvas.height >= pageWidth/pageHeight ? pageWidth/canvas.width : pageHeight/canvas.height;

    if (this.state.outputFormat === 'PNG') {
        canvas.toBlob( (blob) => {
            FileSaver.saveAs(blob, 'map.png');
        });
    }
    else {
        var imgData = canvas.toDataURL('image/png', 1.0);
        var pdf = new jsPDF(this.state.orientation, 'mm', this.state.format); // mm or undefined
        pdf.addImage(imgData, 'PNG', 0, 0, canvas.width * ratio, canvas.height * ratio);
        pdf.save(`map-${this.state.paper}-${this.state.orientation}.pdf`);
    }
};


setDPI(canvas, dpi) {
    var gl = canvas.getContext('webgl') || canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
    var scaleFactor = dpi / 96;
    var displayWidth  = Math.floor(gl.canvas.clientWidth * scaleFactor);
    var displayHeight = Math.floor(gl.canvas.clientHeight * scaleFactor);

    if (gl.canvas.width  !== displayWidth || gl.canvas.height !== displayHeight) {
        gl.canvas.width  = displayWidth;
        gl.canvas.height = displayHeight;
        // added but doesnt change
        gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
    }
};

我的代码中的问题是,如果我将scaleFactor与高度相乘,则返回黑色图像;如果我recome scaleFactor向我显示图像,但不调整大小或应用dpi。

0 个答案:

没有答案