简体   繁体   中英

Preventing canvas from clearing image using Javascript

I appreciate your help on this:

I have a code that adds an image to a canvas using 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);
    }

The image was added successfully; however, the clear button removes it. Is there a way I can prevent clear button from erasing the image?

Thanks in Advance

The only way is, re-drawing the image after clearing the canvas.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM