在HTML Canvas上绘制多个路径

时间:2019-03-18 20:28:27

标签: javascript html css canvas html5-canvas

您好,我的HTML画布出现问题,当我在画布上从一个接触点连续绘制一个连续的长笔触时,它的效果很好。是否可以先绘制然后停下来再绘制一次,依此类推。即只是用画布绘制多次,而不仅是连续笔划?喜欢能够画脸吗?请参阅下面的代码。感谢任何帮助。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>


<style>
canvas { border: 5px solid blue }

</style>

</head>
<body>
<canvas id="c" width="500" height="300"></canvas>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>


<script>
function midPointBtw(p1, p2) {
  return {
    x: p1.x + (p2.x - p1.x) / 2,
    y: p1.y + (p2.y - p1.y) / 2
  };
}

function getPattern() {
  return ctx.createPattern(img, 'repeat');
}


var el = document.getElementById('c');
var ctx = el.getContext('2d');

ctx.lineWidth = 50;
ctx.lineJoin = ctx.lineCap = 'round';

var img = new Image;
img.onload = function() {
  ctx.strokeStyle = getPattern();
};
img.src = "https://i.postimg.cc/rF2R0GRY/dick2.png";

var isDrawing, points = [];




var getXY = function(e) {
  var source = e.touches ? e.touches[0] : e;

  return {
    x: source.clientX,
    y: source.clientY
  };
};

var startDrawing = function(e) {
  isDrawing = true;
  points.push(getXY(e));
  event.preventDefault();

};


var keepDrawing = function(e) {
  if (!isDrawing) return;

  points.push(getXY(e));
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  var p1 = points[0];
  var p2 = points[1];

  ctx.beginPath();
  ctx.moveTo(p1.x, p1.y);

  for (var i = 1, len = points.length; i < len; i++) {
    var midPoint = midPointBtw(p1, p2);
    ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
    p1 = points[i];
    p2 = points[i + 1];
  }
  ctx.lineTo(p1.x, p1.y);
  ctx.stroke();
  event.preventDefault();
};


var stopDrawing = function() {
  isDrawing = false;
  points = [];
};

el.addEventListener('touchstart', startDrawing);
el.addEventListener('mousedown', startDrawing);

el.addEventListener('touchmove', keepDrawing);
el.addEventListener('mousemove', keepDrawing);

el.addEventListener('touchend', stopDrawing);
el.addEventListener('mouseup', stopDrawing);

function clearCanvas(canvas,ctx) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }



</script>


<form id ="search">
<input type = "text" name="message" id="user_input">
<input type = "submit" value="Clear Sketchpad" id="clearbutton" 
 onclick="clearCanvas(canvas,ctx);">
</form>



<p><span id='display'></span></p>

</body>
</html>

1 个答案:

答案 0 :(得分:-1)

您正在使用keepDrawing函数清除画布。尝试删除显示以下内容的行:

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

在该功能中,然后重试。您只需在用户选择按钮时清除画布。