我不知道为什么,但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),因此您的矩形尺寸未定义或为 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。
关于javascript - 无法清除 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32893031/