防止画布使用Javascript清除图像

时间:2017-06-01 07:11:24

标签: javascript canvas drawing

感谢您对此的帮助:

我有一个使用Javascript将图像添加到画布的代码:

  var canvas = document.getElementById('QID8-Signature'),
    context = canvas.getContext('2d');
    base_image = new Image();
    base_image.src = 'https://adec.qualtrics.com/CP/Graphic.php?IM=IM_dmAm33It7ShDqAt';
    base_image.onload = function(){
    context.drawImage(base_image, 216, 168);
    }

图片已成功添加;但是,清除按钮会将其删除。有没有办法阻止清除按钮擦除图像?

先谢谢

1 个答案:

答案 0 :(得分:0)

唯一的方法是在清除画布后重新绘制图像。



var clear = document.getElementById('QID10-ClearSignature'),
   canvas = document.getElementById('QID8-Signature'),
   context = canvas.getContext('2d'),
   base_image = new Image(),
   imgLoaded = false;
   
base_image.onload = function() {
   imgLoaded = true;
   context.drawImage(base_image, 0, 0, 216, 168);
   context.fillRect(10, 10, 20, 20);
};
base_image.src = 'https://adec.qualtrics.com/CP/Graphic.php?IM=IM_dmAm33It7ShDqAt';

clear.onclick = function(e) {
   e.preventDefault();
   if (!imgLoaded) return;
   context.clearRect(0, 0, canvas.width, canvas.height);
   context.drawImage(base_image, 0, 0, 216, 168);
}

canvas{border: 1px solid #ccc}

<button><span id="QID10-ClearSignature" class="ClearSignature">clear</span></button><br>
<canvas id="QID8-Signature" width="216" height="168"></canvas>
&#13;
&#13;
&#13;