简体   繁体   中英

Unable to clear the canvas

I don't know why, but the clearRect() does not work. This is a function that is executed every time I click on a panel or every time I change the thickness' value.

//When click on a menu section
$(".menuSection").click(function() {
//Show hide the selected item
$(this).next().toggle();
//hide all the other panels
$(this).next().siblings(".panel").hide();
//To update the values in the colors panel when selected
if ( $(this).prop("id") == "colors" ) {
    changeColorBySliders();
}
if ( $(this).prop("id") == "pen" ) {
     updatePreview();
}
});

//when thickness slider change:
$("#penPanel input[type=range]").on("input", updatePreview);

The fact is that it draws the line, but if I click it again it's doesn't reset.

var $preview = $("#preview");
var contextPreview = $preview[0].getContext("2d");

//Function to update the pen's preview
function updatePreview() {
  console.log($("#thickness").val());
  var rgba = $("#mainCanvas").css("background-color");
  $("#preview").css("background-color", rgba);
  //Resetting the preview
  contextPreview.clearRect(0, 0, $preview.width, $preview.height);
  //Drawing an example path
  contextPreview.beginPath();
  contextPreview.moveTo(50, 30);
  contextPreview.lineTo(100, 110);
  contextPreview.quadraticCurveTo(115, 120, 125, 80);
  contextPreview.bezierCurveTo(145, -40, 150, 120, 200, 95);
  contextPreview.lineTo(250, 65);
  contextPreview.lineWidth = $("#thickness").val();
  contextPreview.strokeStyle = color;
  contextPreview.stroke();
  contextPreview.closePath();
}

Any help?

Solution

I solved the problem using this kind of declaration:

var preview = document.getElementById("preview");
var contextPreview = preview.getContext("2d");
contextPreview.clearRect(0, 0, preview.width, preview.height);

Insted of the jquery one:

var $preview = $("#preview");
var contextPreview = $preview[0].getContext("2d");

Why?

it's because $preview is a jQuery object, $preview.width is therefore a function , so when you called clearRect() , you were actually calling contextPreview.clearRect(0,0, function, function) so your rect dimensions were undefined or 0 so it wasn't clearing a single pixel.

So you can still use jQuery but be sure you call contextPreview.clearRect(0,0, $preview[0].width, $preview[0].height)

var preview = document.getElementById("preview");
var contextPreview = preview.getContext("2d");
contextPreview.clearRect(0,0, $preview[0].width, $preview[0].height)

Special Thanks to Kaiido.

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