gpt4 book ai didi

javascript - 如何在 Canvas 中绘制两个具有样式的图像?

转载 作者:行者123 更新时间:2023-11-28 04:27:37 25 4
gpt4 key购买 nike

我想在一个 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 inside 框放在同一 Canvas 上。这可能吗? enter image description here

最佳答案

我不太确定这是你需要的

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>

关于javascript - 如何在 Canvas 中绘制两个具有样式的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52534718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com