如何在画布上绘制两个风格的图像?

时间:2018-09-27 10:18:47

标签: javascript html html5 canvas html5-canvas

我想在单个画布上绘制两个具有某种样式的图像。我的要求是这样的: 我尝试过:

<canvas id="viewport" width="1000" height="1000"></canvas>
canvas {
  border: 1px solid blue;
    width: 100%;
    height:auto;
    border-bottom-left-radius: 100%;
    border-bottom-right-radius: 100%;
    overflow: hidden;
}

我的JavaScript:

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

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'light-landscape.jpg';
  base_image.onload = function(){
    context.drawImage(base_image, 0, 0,canvas.width, canvas.height);
  }
}

但是这种样式是为Image1设计的。如何将Image2内部框放在同一画布上。 这可能吗? enter image description here

1 个答案:

答案 0 :(得分:7)

我不太确定这是您所需要的

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
let cw = canvas.width = 1000,
  cx = cw / 2;
let ch = canvas.height = 1000,
  cy = ch / 2;



make_base('https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/beagle400.jpg',0,0,cw,ch);
make_base('https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/apple.png',500,500,100,100);

function make_base(url,x,y,w,h)
{
  let base_image = new Image();
  base_image.src = url;
  base_image.onload = function(){
    context.drawImage(base_image, x, y,w, h);
  }
}
canvas {
  border: 1px solid blue;
    width: 100%;
    height:auto;
    border-bottom-left-radius: 100%;
    border-bottom-right-radius: 100%;
    overflow: hidden;
}
<canvas id="viewport" width="1000" height="1000"></canvas>

更新: 在这种情况下,我必须使用clip()方法剪切第一张图像。

const ctxa = a.getContext("2d");
const ctxb = b.getContext("2d");
const ctxc = c.getContext("2d");


let cw = a.width = b.width = c.width = 1000;
let ch = a.height = b.height = c.height = 1000;


// using clip() to cut the first canvas
ctxa.beginPath();
ctxa.moveTo(0,0)
ctxa.lineTo(0,500)
ctxa.arc(500,500,500,Math.PI,0,true);
ctxa.lineTo(1000,0);
ctxa.closePath();
ctxa.clip();

make_base(ctxa,'https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/beagle400.jpg',0,0,cw,ch);
make_base(ctxb,'https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/apple.png',0,0,cw,ch);

function make_base(ctx,url,x,y,w,h)
{
  let base_image = new Image();
  base_image.src = url;
  base_image.onload = function(){
  ctx.drawImage(base_image, x, y,w, h);
  }
}


button.addEventListener("click",()=>{
  let imga = a;
  let imgb = b;
  ctxc.drawImage(imga,0,0,cw,ch,200,0,600,600); 
  ctxc.drawImage(imgb,0,0,cw,ch,400,800,200,200); 
  
})
#a, #b,#c{width:100px; border: 1px solid blue;}
<canvas id="a" width="1000" height="1000"></canvas>
<canvas id="b" width="1000" height="1000"></canvas>
<canvas id="c" width="1000" height="1000"></canvas>

<button id="button">click</button>