Splicee
Splicee

Reputation: 73

How add image to canvas by layers?

This is my code:

var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(55, 95, 30, 0, 2 * Math.PI);

var ctx1 = c.getContext("2d");
ctx1.rect(0, 0, 200, 300);
ctx.clip();
ctx.stroke();

var canvas = document.getElementById('myCanvas'),
    context = canvas.getContext('2d');

make_base();

function make_base() {
  base_image = new Image();
  base_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/default=&s=80';
  base_image.onload = function() {
    context.drawImage(base_image, 15, 55);
  }
}
canvas {
  border: 1px solid #000000;
  position: absolute;
  top: 66px;
  left: 22px;
}
<canvas id="myCanvas" width="236" height="413"></canvas>

From my code above I try to add image in to the circle and rectangle I have done with add image in circle I try to add one more image in to the rectangle for the background but it seem not works.

Upvotes: 3

Views: 59

Answers (1)

Ionut Necula
Ionut Necula

Reputation: 11472

You just need to create a second image and position it accordingly. Also use only one context, there is no need to declare it multiple times. Modified your code. I hope this will help you:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(55, 95, 30, 0, 2 * Math.PI);
ctx.rect(18, 150, 200, 250);
ctx.clip();
ctx.stroke();

make_base();

function make_base() {
  base_image = new Image();
  base_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?default=&s=80';
  base_image.onload = function() {
    ctx.drawImage(base_image, 15, 55);
  }
  second_image = new Image();
  second_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?default=&s=80';
  second_image.onload = function() {
    ctx.drawImage(second_image, 19, 151);
  }
}
<canvas id="myCanvas" width="236" height="413" style="border:1px solid #000000; position:absolute; top:66px; left:22px;"></canvas>

Upvotes: 1

Related Questions