Michal Michal - 2 months ago 19
HTML Question

adding multiple drawImage() to one canvas

I have problem with adding multiple drawings to one canvas. I made some example:
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);


Code isn't drawing the second red line in last line of js code. How to fix it?

Answer

This JS will draw the red line fully ( Or mostly; depending on where you want it.) (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) // This calls the function draw() which draws each line

The draw() function in the code takes the 4 params you had set for example.

It would be best to draw the black line the same way, i.e. Take it out of the function or take it out of function and add another draw() call for the black line.

15 = TOP X Axis, 56 = TOP Y Axis, 200 = Bottom X Axis, 150 = Bottom Y Axis

You could also add another param for color to your function like so:

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")