且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript:在画布上绘制矩形在IE上不工作

更新时间:2023-11-24 09:05:34

/ strong>

Problem

您正在使用 context2.rect 绘制矩形,这是一个路径命令。

You are drawing rectangles with context2.rect which is a path command.

路径命令由画布记住,直到发出新的 context2.beginPath 为止

Path commands are "remembered" by the canvas until a new context2.beginPath is issued

因此,当您执行 context2.stroke

时,所有先前的rect都会被记住并重新绘制修复

Fix

只需将context2.beginPath放在mousemove事件处理程序中: http://jsfiddle.net/m1erickson/A8ge6/

Just put context2.beginPath in your mousemove event handler: http://jsfiddle.net/m1erickson/A8ge6/

canvas2.addEventListener("mousedown",startLine);
canvas2.addEventListener("mouseup",drawLine);
    canvas2.addEventListener('mousemove', function (evt) {
        var rect = canvas2.getBoundingClientRect();
        x = evt.clientX - rect.left;
        y = evt.clientY - rect.top;
        if (clicked) {
            canvas2.width = canvas2.width;
            console.log(xStart);

            // add beginPath so previous context2.rect's are dismissed
            context2.beginPath();

            context2.rect(xStart, yStart, x - xStart, y - yStart);
            context2.stroke();
        }
    }, false);