更改 Canvas 删除图像

Changing Canvas Removes Image

我正在以类似于 T 恤编辑器的方式使用 HTML canvas,允许用户定位和调整图像大小。图像被绘制到 canvas 上,如下所示:

var img = new Image();
img.crossOrigin='anonymous';
img.onload = function () {
    var ratio = img.width / img.height;

    imageWidth = canvas.width;
    imageHeight = imageWidth / ratio;
    imageY = (canvas.height-imageHeight)/2;
    if (imageHeight > canvas.height) {
        imageHeight = canvas.height;
        imageWidth = imageHeight * ratio;
        imageY = 0;
    }

    imageRight = imageX + imageWidth;
    imageBottom = imageY + imageHeight
    draw(true, false);
}

function draw(withAnchors, withBorders) {

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);

    if (withAnchors) {
        drawDragAnchor(imageX, imageY);
        drawDragAnchor(imageRight, imageY);
        drawDragAnchor(imageRight, imageBottom);
        drawDragAnchor(imageX, imageBottom);
    }

    if (withBorders) {
        ctx.beginPath();
        ctx.moveTo(imageX, imageY);
        ctx.lineTo(imageRight, imageY);
        ctx.lineTo(imageRight, imageBottom);
        ctx.lineTo(imageX, imageBottom);
        ctx.closePath();
        ctx.stroke();
    }

}

绘制到 canvas 上的实际图像是使用 PHP 在我的主 index.php 文件中设置的,如下所示:

<script type="text/javascript"> img.src = <?php echo json_encode($image_url); ?>; </script>

canvas 的大小因产品而异,我会在用户更改产品时动态更改 canvas 的大小,如下所示:

var changeCanvas = document.getElementById("editorCanvas");
canvas.width = 71;
canvas.height = 285;

我的问题是每当我更改 canvas 的大小时,绘制在其上的图像就会消失。但是,每当我单击或移动 canvas 时,它都会奇怪地重新出现。我想知道我做错了什么以及如何解决这个问题?


鼠标操作:

$("#editorCanvas").mousedown(function (e) {
    handleMouseDown(e);
});
$("#editorCanvas").mousemove(function (e) {
    handleMouseMove(e);
});
$("#editorCanvas").mouseup(function (e) {
    handleMouseUp(e);
});
$("#editorCanvas").mouseout(function (e) {
    handleMouseOut(e);
});

这是设计使然。 standard states(我强调):

When the user agent is to set bitmap dimensions to width and height, it must run the following steps:

[...]

  • Resize the scratch bitmap to the new width and height and clear it to fully transparent black.

所有内容在 canvas 改变大小后必须重新绘制。

您可能已经(虽然当前未显示)添加了触发重绘的鼠标事件侦听器。

使用 draw 函数重新绘制图像的代码:draw(true, false);