gpt4 book ai didi

javascript - myContext.clearRect(0, 0, 500, 700);未正确清除 Canvas

转载 作者:行者123 更新时间:2023-12-02 19:10:55 25 4
gpt4 key购买 nike

我有一个可以用鼠标绘制的 HTML5 Canvas。我希望能够清除 Canvas ,以便用户可以制作新的绘图。我这样做是:

myContext.clearRect(0, 0, 500, 700);

Canvas 看起来很清晰,但一旦用户开始新绘图,旧绘图就会重新出现。我的鼠标绘图部分的 JavaScript 是:

// Variables
var x1;
var y1;
var isPressed = false;
var myCanvas;
var myContext;

function startCanvas() {

// Canvas stuff
myCanvas = document.getElementById("can1");
myContext = myCanvas.getContext("2d");

// Specify a black background, and white lines that are 3 pixels thick.
myContext.fillStyle = '#000000';
myContext.strokeStyle = '#000000';
myContext.fillRect(0, 0, 500, 700);
myContext.lineWidth = 3;
myContext.fill();
}

function functionMouseDown(e) {
// Get coordinates
x1 = e.clientX - myCanvas.offsetLeft;
y1 = e.clientY - myCanvas.offsetTop;

isPressed = true;
}

function functionMouseMove(e) {
// If mouse is down and moved start drawing line
if (isPressed == true) {
drawLine(e);
}
}

function functionMouseUp() {
// Stop drawing line
isPressed = false;
}

function drawLine(e) {
// Draw line
var x = e.clientX - myCanvas.offsetLeft;
var y = e.clientY - myCanvas.offsetTop;

myContext.strokeStyle = '#ffffff';
myContext.lineWidth = 1;
myContext.moveTo(x1, y1);
myContext.lineTo(x, y);
myContext.stroke();

// Set start coordinates to current coordinates
x1 = x;
y1 = y;
}

startCanvas();

HTML 是:

<canvas id="can1" width="500" height="700"></canvas>

最佳答案

myContext.strokeStyle = '#000000';
myContext.beginPath();//<---- add this and read about this.
myContext.fillRect(0, 0, 500, 700);
myContext.lineWidth = 3; //why?
myContext.fill();

关于javascript - myContext.clearRect(0, 0, 500, 700);未正确清除 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13739237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com