将多个 drawImage() 添加到一个 canvas

adding multiple drawImage() to one canvas

我在将多个绘图添加到一个 canvas 时遇到问题。我做了一些例子: https://jsfiddle.net/ym5q9ktp/

HTML:

<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML5 canvas tag.
</canvas>

JS:

function lc(canv, x1, y1, x2, y2) {
  c = canv.getContext("2d");
  c.beginPath();
  c.moveTo(x1, y1);
  c.lineTo(x2, y2);
  c.strokeStyle = "red";
  c.stroke();
  return c
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

ctx.drawImage(lc(canvas, 15, 56, 56, 75), 10, 10);
ctx.drawImage(lc(canvas, 25, 56, 156, 95), 80, 80);

代码没有在最后一行 js 代码中绘制第二条红线。如何解决?

此 JS 将完全绘制红线(或大部分;取决于您想要的位置。)(Live Fiddle):

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var draw = function(var1, var2, var3, var4) {
ctx.beginPath();
ctx.moveTo(var1, var2);
ctx.lineTo(var3, var4);
ctx.stroke();
}

draw(0, 0, 200, 50)
draw(0, 10, 200, 60)

draw(15, 56, 200, 150) // 这会调用绘制每条线的函数 draw()

代码中的draw()函数以您设置的4个参数为例。

最好以同样的方式绘制黑线,即将其从函数中取出或将其从函数中取出并为黑线添加另一个 draw() 调用。

15 = 顶部 X 轴,56 = 顶部 Y 轴,200 = 底部 X 轴,150 = 底部 Y 轴

您还可以像这样为您的函数添加另一个颜色参数:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var draw = function(var1, var2, var3, var4, color) {
    ctx.beginPath();
    ctx.strokeStyle = color; // Takes the fifth param "color"
    ctx.moveTo(var1, var2);
    ctx.lineTo(var3, var4);
    ctx.stroke();
}

draw(0, 0, 200, 50, "red")
draw(0, 10, 200, 60, "black")