Html 画布中的脉冲动画

Html 画布中的脉冲动画,html,canvas,Html,Canvas,我试图让各种形状在画布上产生脉冲般的效果,并设法用一个圆圈来完成 function drawCircle() { // color in the background context.fillStyle = "#EEEEEE"; context.fillRect(0, 0, canvas.width, canvas.height); // draw the circle context.beginPath(); var radius = 25 + 20 * Math.abs(Math.co

我试图让各种形状在画布上产生脉冲般的效果,并设法用一个圆圈来完成

function drawCircle() {

// color in the background
context.fillStyle = "#EEEEEE";
context.fillRect(0, 0, canvas.width, canvas.height);

// draw the circle
context.beginPath();

var radius = 25 + 20 * Math.abs(Math.cos(angle)); //radius of circle
context.arc(25, 25, radius, 0, Math.PI * 2, false); //position on canvas
context.closePath();

// color in the circle
context.fillStyle = "#006699";
context.fill();

//'pulse'
angle += Math.PI / 220;

requestAnimationFrame(drawCircle);
}
drawCircle();
但是我不知道该怎么做其他的形状。到目前为止,我对三角形的理解是

function drawTriangle() {

// draw the triangle
context.beginPath();
context.moveTo(75, 50);
context.lineTo(100, 75);
context.lineTo(100, 25);
context.fill();

context.rect(215, 100, Math.PI * 2, false); //position on canvas
context.closePath();

// color in the triangle
context.fillStyle = "#3f007f";
context.fill();

//'pulse'
angle += Math.PI / 280;

requestAnimationFrame(drawTriangle);
}
drawTriangle();

任何洞察都将不胜感激。

这可以通过改变上下文矩阵的规模来实现

您只需找到形状的缩放定位点的位置,以便在应用缩放后将矩阵平移到正确的位置

在下面的示例中,我将使用形状的中心作为缩放锚点,因为它似乎是您想要的

矩阵变换的扩展版本是

ctx.translate(anchorX, anchorY);
ctx.scale(scaleFactor, scaleFactor);
ctx.translate(-anchorX, -anchorY);
在下面的例子中,它被简化为

ctx.setTransform(
   scale, 0, 0,
   scale, anchorX  - (anchorX * scale), anchorY  - (anchorY * scale)
);
var ctx=canvas.getContext('2d');
var角=0;
var量表=1;
var img=新图像();
img.src=https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png';
动漫();
函数anim(){
clearRect(0,0,canvas.width,canvas.height);
updateScale();
画圈();
drawTriangle();
drawImage();
setTransform(1,0,0,1,0,0);
请求动画帧(anim);
}
函数updateScale(){
角度+=数学PI/220;
比例=0.5+数学绝对值(数学绝对值(角度));
}
函数drawCircle(){
ctx.beginPath();
变量cx=75,
cy=50,
半径=25;
//对于圆,给出了centerX和centerY
var anchorX=cx,
anchorY=cy;
//有了这些主播,主播和音阶,
//我们可以确定在什么地方需要翻译上下文
var scaledX=anchorX-(anchorX*比例),
scaledY=锚定-(锚定*标度);
//然后,我们一次应用该矩阵
setTransform(scale,0,0,scale,scaledX,scaledY);
//我们正常画画
ctx.弧(cx,cy,半径,0,数学PI*2);
ctx.fill();
}
函数drawTriangle(){
ctx.beginPath();
//对于三角形,我们需要找到minX和maxX之间的位置,
//在minY和maxY之间
var anchorX=175+(200-175)/2,
anchorY=25+(75-25)/2;
var scaledX=anchorX-(anchorX*比例),
scaledY=锚定-(锚定*标度);
setTransform(scale,0,0,scale,scaledX,scaledY);
ctx.moveTo(175,50);
ctx.lineTo(200,75);
ctx.lineTo(200,25);
ctx.fill();
}
函数drawImage(){
如果(!img.naturalWidth)返回;
//对于矩形,它只是pos+(长度/2)
var anchorX=250+img.naturalWidth/2,
anchorY=25+img.自然高度/2;
var scaledX=anchorX-(anchorX*比例),
scaledY=锚定-(锚定*标度);
setTransform(scale,0,0,scale,scaledX,scaledY);
ctx.drawImage(img,250,25);
}