7

还记得金碟豹唱片的图标吗?我用canvas实现了它

 2 years ago
source link: https://blog.51cto.com/u_15460453/5680442
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

还记得金碟豹唱片的图标吗?我用canvas实现了它

相信九零后们的同学们都看过金碟豹唱片,最经典的莫过于的它的图标从电视这边跳到那边了,那么这个跳动是怎么实现的呢?今天我就用canvas给大家实现下

首先定义画布,画布是正方形的,并显示边框

html部分:

<canvas id="jay" width="500" height="500"></canvas>

css部分:

canvas {
            margin: 0 auto;
            border: 2px solid #94b61b;
            display: block;
        }

这样相当于一个电视剧画好了😋,接下来我们使用canvas画一个圆

ctxJay.beginPath();
ctxJay.arc(x, y, r, 0, Math.PI * 2);

为了让圆能动起来,我们需要通过定时任务的方法不断执行这个画圆的动作

setInterval(function () {
        ctxJay.clearRect(0,0,width,height);
        drawCircle(x, y, r);
    }, 40);

这样就可以不停的进行画圆了,但是有一个问题就是之前画的圆没有被清除,这样会导致之前画的也存在,我们调用clearRect()清除调之前画的圆,这样视觉效果上一个圆就动起来了

小球的反弹

我们还需要做的工作的是,当小球到达边缘的时候实现反弹的效果,这种实现我们可以定义一个速度的变量,正向的速度是正的值,反向的速度就是负的值,有点像物理学的东西了,当到达边界的时候,速度改为相反值就可以了

if (x-r<=0 || x+r>width) {
   xSpeed = -xSpeed;
}
x+=xSpeed;

同理,y的值也是这么变化

可以调节xSpeed ySpeed控制球的速度,当两者速度不一致的时候角度就产生了偏移

加载图片的操作需要我们创建一个Image对象,设置onload事件,调用stroke()方法进行绘制

let img = new Image();
img.src = 'https://xiepanpan123.oss-cn-beijing.aliyuncs.com/图片1.png';
img.onload = () => {
    img.width = 60;
    img.height = 60;

    ctxJay.drawImage(img,x-r, y-r, img.width, img.height);
}
ctxJay.strokeStyle = "orange";
ctxJay.stroke();

最后我们再写上金碟豹的文字,大功告成

ctxJay.fillText("金碟豹",x-r/2,y+r+20);

这篇文章主要使用canvas来绘制了一个类似金碟豹logo的效果,主要使用了canvas的画圆的操作和清除功能,还有图片的加载,设置定时任务等功能,你也来试试吧!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK