将图像绘制到画布有时不显示任何东西

Drawing Image to Canvas Sometimes Doesn't Display Anything

本文关键字:显示 任何东 图像 绘制      更新时间:2023-09-26

我正在尝试学习画布,我遇到了一个奇怪的故障,我无法弄清楚,虽然我确信这只是一些愚蠢的我忽略了。基本上,我有一个页面,您可以在其中选择本地图像文件。然后它会把它绘制到一个已经调整大小以适合图像的画布上,当你将鼠标移动到图像上时,它会给出光标的坐标并显示一些指导线。

页在这里。

我遇到的问题是,当你选择一个文件时,它会随机调整画布的大小到0x0,从那一点开始,无论你选择什么图像文件,它都会保持在那个大小。如果您刷新页面并选择上次导致问题的相同图像文件,那么它可能会正常工作并显示(也可能不会)。

我不认为这是一个浏览器缓存问题,因为我看到它发生在我选择File1,它工作正常,选择File2,它工作正常,然后再次选择File1,它坏了。此外,如果我理解正确的话,那么将FileReader的事件处理程序设置为onloadend应该可以避免在完全读取图像之前试图绘制图像的任何问题。

这是我的代码(我相信有更简洁的方法,但我仍在学习)。如有任何帮助,我将不胜感激。

index . html

<!DOCTYPE html>
<head>
    <title>Image Coordinates Inspector</title>  
    <style>
        body {
            background: #4a4a4a;
            color: #fdcd00;
        }   
        #canvas {
            margin-left: 15px;
            background: #ffffff;
            border: thin inset rgba(100, 150, 230, 0.5);
            cursor: crosshair;
            display: none;
        }
        #coordinates {
            margin-left: 15px;
        }   
        #fileselect {
            margin-left: 10px;
        }
    </style>
    <script language="JavaScript" type="text/javascript" src="imgcoords.js"></script>
</head>
<body onload="initializePage()">
    <div id='fileselect'>
        <form>
            <input id="filename" name="filename" type="file" accept="image/*">
        </form>
    </div>
    <div id='coordinates'></div>
    <canvas id='canvas'>
        Canvas not supported.
    </canvas>
</body>
</html>

imgcoords.js

var canvas,
    coordinates,
    filename,
    context,
    img = new Image(),
    coordevent = false;
function initializePage() {
    canvas = document.getElementById('canvas');
    coordinates = document.getElementById('coordinates');
    filename = document.getElementById('filename');
    context = canvas.getContext('2d');
    filename.onchange = function(e) {
        validateFile();
        e.preventDefault();
    };
}
function validateFile() {
    if (filename.value != '' && filename.files[0].type.match(/image.*/)) {
        var file = filename.files[0],
            reader = new FileReader();
        canvas.style.display = "none";
        reader.readAsDataURL(file);
        reader.onloadend = function(e) {
            img.src = e.target.result;
            resizeCanvas();
            drawImageFile();
        };
    } else {
        canvas.style.display = "none";
        alert("Selected file is not a valid image file.");
    }
}
function resizeCanvas() {
    canvas.width = img.width;
    canvas.height = img.height;
}
function windowToCanvas(canvas, x, y) {
    var bbox = canvas.getBoundingClientRect();
    return { x: (x - bbox.left) * (canvas.width / bbox.width),
             y: (y - bbox.top) * (canvas.height / bbox.height)
    };
}
function clearCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}
function drawImageFile() {
    clearCanvas();
    context.drawImage(img, 0, 0);
    if (!coordevent) {
        canvas.onmousemove = function(e) {
            var loc = windowToCanvas(canvas, e.clientX, e.clientY);
            drawImageFile();
            drawGuidelines(loc.x, loc.y);
            updateCoordinates(loc.x, loc.y);
        };
        coordevent = true;
    }
    updateCoordinates(0, 0);
    canvas.style.display = "inline";
}
function drawGuidelines(x, y) {
    context.strokeStyle = 'rgba(0, 0, 230, 0.8)';
    context.lineWidth = 0.5;
    drawVerticalLine(x);
    drawHorizontalLine(y);
}
function updateCoordinates(x, y) {
    coordinates.innerHTML = '(' + x.toFixed(0) + ', ' + y.toFixed(0) + ')';
}
function drawHorizontalLine(y) {
    context.beginPath();
    context.moveTo(0, y + 0.5);
    context.lineTo(context.canvas.width, y + 0.5);
    context.stroke();
}
function drawVerticalLine(x) {
    context.beginPath();
    context.moveTo(x + 0.5, 0);
    context.lineTo(x + 0.5, context.canvas.height);
    context.stroke();
}

顺便说一句,你有一个很好的测量工具!

改变:

reader.onloadend = function(e) {
    img.src = e.target.result;
    resizeCanvas();
    drawImageFile();
};

To this——为了给img加载所需的时间:

reader.onloadend = function(e) {
    img.onload=function(){
        resizeCanvas();
        drawImageFile();
    }
    img.src = e.target.result;
};

另外,还有一个新的Chrome bug,你可能想要避免像这样:

// img = new Image() is buggy in Chrome
img = document.createElement("img"),