Невозможно рисовать на холсте HTML5

Aug 28 2020

Я создал холст с разрешением Hi dpi, а затем попытался нарисовать рамку, но что-то пошло не так. Почему я не могу рисовать на холсте, может ли кто-нибудь мне помочь?

Ошибок не произошло, функция рисования выполняется, но результата нет

var HiDPICanvas = function(container_id, color, w, h) {
    /*
    canvas will be placed in the container
    canvas will have width w and height h
    */
    
    var ratio = function() {
        // return pixel ratio
        var ctx = document.createElement("canvas").getContext("2d");
        var dpr = window.devicePixelRatio || 1;
        var bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1;
    
        return dpr / bsr;
    }

    var createHiDPICanvas = function() {
        if (!ratio) { ratio = ratio(); }
        var chart_container = document.getElementById(container_id);
        var can             = document.createElement("canvas");
        can.style.backgroundColor = color
        can.width           = w * ratio;
        can.height          = h * ratio;
        can.style.width     = w + "px";
        can.style.height    = h + "px";
        can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
        chart_container.appendChild(can);
        return can;
    }

    var canvas = createHiDPICanvas()
    return {
        canvas : canvas,
        ctx    : canvas.getContext("2d"),
        width  : w,
        height : h,
        color  : color
    }

}

// cci -> canvas ctx info (dict)
var cci = HiDPICanvas("lifespanChart", "bisque", 780, 640)
var ctx           = cci.ctx
var canvas        = cci.canvas

var Box = function(color) {
    
    var create = function() {
        ctx.save();
        ctx.globalCompositeOperation = "source-over";
        ctx.beginPath();
        ctx.lineWidth = 0.001;
        ctx.fillStyle = color;
        ctx.moveTo(-1, -1);
        ctx.lineTo(50, -1)
        ctx.lineTo(50, 50)
        ctx.lineTo(-1, 50)
        ctx.lineTo(-1, -1)
        console.log("drawing square")
        ctx.stroke();
        ctx.closePath();
        ctx.fill();
        ctx.restore()
    }

    create()
    return {
        refresh : create,
        color   : color
    }
    
}


var borders = Box("red")
<div>
        <div id="lifespanChart"></div>
    </div>

Он должен рисовать коробку, но это не так, что я забыл сделать?

Здесь добавлен текст, потому что он не позволяет мне задавать quesiton из-за большого количества кода, но мне больше нечего описывать

заранее спасибо

Ответы

2 Anton Aug 28 2020 at 02:57

Вы напортачили с ratio. Это одновременно и переменная, и функция ...

Я меняю имя функции на getRatioи добавляю переменную. В настоящее время работает:

var HiDPICanvas = function(container_id, color, w, h) {
    /*
    canvas will be placed in the container
    canvas will have width w and height h
    */
    
    var getRatio = function() {
        // return pixel ratio
        var ctx = document.createElement("canvas").getContext("2d");
        var dpr = window.devicePixelRatio || 1;
        var bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1;
    
        return dpr / bsr;
    }

    var createHiDPICanvas = function() {
        let ratio = getRatio();
        var chart_container = document.getElementById(container_id);
        var can             = document.createElement("canvas");
        can.style.backgroundColor = color
        can.width           = w * ratio;
        can.height          = h * ratio;
        can.style.width     = w + "px";
        can.style.height    = h + "px";
        can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
        chart_container.appendChild(can);
        return can;
    }

    var canvas = createHiDPICanvas()
    return {
        canvas : canvas,
        ctx    : canvas.getContext("2d"),
        width  : w,
        height : h,
        color  : color
    }

}

// cci -> canvas ctx info (dict)
var cci = HiDPICanvas("lifespanChart", "bisque", 780, 640)
var ctx           = cci.ctx
var canvas        = cci.canvas

var Box = function(color) {
    
    var create = function() {
        ctx.save();
        ctx.globalCompositeOperation = "source-over";
        ctx.beginPath();
        ctx.lineWidth = 0.001;
        ctx.fillStyle = color;
        ctx.moveTo(-1, -1);
        ctx.lineTo(50, -1)
        ctx.lineTo(50, 50)
        ctx.lineTo(-1, 50)
        ctx.lineTo(-1, -1)
        console.log("drawing square")
        ctx.stroke();
        ctx.closePath();
        ctx.fill();
        ctx.restore()
    }

    create()
    return {
        refresh : create,
        color   : color
    }
    
}


var borders = Box("red")
<div>
        <div id="lifespanChart"></div>
    </div>