简体   繁体   中英

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM