将图像绘制到画布有时不显示任何内容

时间:2013-06-19 06:02:26

标签: javascript image html5-canvas

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

页面为here

我遇到的问题是,当你选择一个文件时,它会随机地将画布大小调整为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();
}

1 个答案:

答案 0 :(得分:1)

BTW,你有很好的测量工具!

改变这个:

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

为此 - 为img提供加载所需的时间:

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

此外,您可能希望避免使用新的Chrome错误:

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