我不知道为什么,但是clearRect()不起作用。
每次单击面板或更改厚度值时都会执行此功能。

//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);


事实是它画了线,但是如果我再次单击它,它不会重置。

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


有什么帮助吗?

最佳答案



我使用这种声明解决了这个问题:

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


插入jquery之一:


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


为什么?

这是因为$ preview是一个jQuery对象,因此$ preview.width是一个函数,所以当您调用clearRect()时,您实际上是在调用contextPreview.clearRect(0,0,function,function),所以您的rect尺寸未定义或为0因此它没有清除单个像素。

因此,您仍然可以使用jQuery,但请确保调用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)


特别感谢Kaiido。

09-10 02:36
查看更多