2016-09-20 104 views
2

我在添加多个图形到一个画布时遇到问题。我做了一些例子: https://jsfiddle.net/ym5q9ktp/将多个drawImage()添加到一个画布中

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代码最后一行第二红线。如何解决它?

回答

0

这个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 = TOP X轴,56 = TOP 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") 
+0

谢谢,它的工作方式:) – Michal