0

I saw this post: Combining two or more Canvas elements with some sort of blending and I am trying to combine my 2 canvases into one for image download. One of my input canvases has a .drawImage function in it. Is there still a way to easily combine 2 canvases into 1 even with my image?

This is my code:

<!DOCTYPE html>
<html>
<body>

<canvas id="canvas1" width="350" height="350" style="border: 1px solid black"></canvas>

<canvas id="canvas2" width="350" height="350" style="border: 1px solid black"></canvas>

<canvas id="canvas3" width="350" height="350" style="border: 1px solid black"></canvas>

<script>
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var img1 = new Image();

img1.onload = function() {
ctx.drawImage(img1, 0, 0);
};

img1.src = 'red.png'


var can2 = document.getElementById('canvas2');
var ctx2 = can2.getContext('2d');

ctx2.beginPath();
ctx2.fillStyle = "pink";
ctx2.arc(50, 50, 50, 0, Math.PI * 2, 1);
ctx2.fill();
ctx2.beginPath();
ctx2.clearRect(20, 40, 60, 20);

var can3 = document.getElementById('canvas3');
var ctx3 = can3.getContext('2d');

ctx3.drawImage(can, 0, 0);
ctx3.drawImage(can2, 0, 0);
</script>

</body>
</html>

Thanks, AppleManYT

Community
  • 1
  • 1

2 Answers2

0

Yes, you can easily combine 2 canvases into 1 even with your image, and to accomplish this you just need to put this ( ctx3.drawImage(can, 0, 0) ) piece of code inside the img1.onload function.

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

var img1 = new Image();
img1.src = 'http://cdn2.boothedog.net/wp-content/uploads/2011/07/boo-the-dog-naked-wednesday--150x150.jpg';
img1.onload = function() {
    ctx.drawImage(img1, 0, 0);
    ctx3.drawImage(can, 0, 0);
};

var can2 = document.getElementById('canvas2');
var ctx2 = can2.getContext('2d');

ctx2.beginPath();
ctx2.fillStyle = "pink";
ctx2.arc(50, 50, 50, 0, Math.PI * 2, 1);
ctx2.fill();
ctx2.clearRect(20, 40, 60, 20);

var can3 = document.getElementById('canvas3');
var ctx3 = can3.getContext('2d');

ctx3.drawImage(can2, 200, 25);
<canvas id="canvas1" width="350" height="150" style="border: 1px solid black"></canvas>
<canvas id="canvas2" width="350" height="150" style="border: 1px solid black"></canvas>
<canvas id="canvas3" width="350" height="150" style="border: 1px solid black"></canvas>
m87
  • 4,445
  • 3
  • 16
  • 31
0

Canvas.. an image that you can draw on.

A canvas is just an image and can be rendered to another canvas just as an image can.

Because the canvas is double buffered (when you render you render to the off screen buffer) you can render the canvas to itself.

You can also use the canvas in place of a DOM tag (I see many example of people converting a canvas to a dataURL just to place on the DOM, this is very memory inefficient)

The general rule is if you can do it with an image, you can use a canvas as well.

Community
  • 1
  • 1
Blindman67
  • 51,134
  • 11
  • 73
  • 136