【问题标题】:Changing Canvas Removes Image更改画布删除图像
【发布时间】:2015-06-27 22:25:06
【问题描述】:

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

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();
    }

}

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

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

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

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

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


鼠标操作:

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

【问题讨论】:

    标签: javascript php html html5-canvas


    【解决方案1】:

    这是设计使然。 standard states(我的重点):

    当用户代理要将位图尺寸设置为宽度和高度时, 它必须运行以下步骤:

    [...]

    • 将暂存位图的大小调整为新的宽度和高度,然后将其清除为完全透明的黑色。

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

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

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

    【讨论】:

    • 感谢您的回答。我实际上有鼠标操作,但它们实际上允许重新定位和调整画布上绘制的图像的大小。我在上面的问题中添加了鼠标操作 - 但实际上我尝试在画布大小更改但没有运气时重绘图像?
    • @AlexSaidani 您是否尝试在设置大小后调用 draw() 方法? (在同一个操作中,就像在 onload 处理程序中一样)
    • 是的,我尝试使用整个 image.onload 函数完全重绘图像,但没有成功,但是通过使用我的主要绘图函数,我设法让它工作:draw(true, false) ;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 2021-04-30
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    相关资源
    最近更新 更多