console
var canvas = document.getElementById("canvasId");
console.log('==>',canvas)
var ctx = canvas.getContext("2d");
var screenWidth = document.documentElement.offsetWidth;
var screenHeight = document.documentElement.offsetHeight;
canvas.width = screenWidth;
canvas.height = screenHeight;
function rand(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
var drawImage = (ctx, url, dx, dy,w = 58, h = 58) => {
return new Promise((res, rej) => {
var img = new Image();
img.onload = () => {
ctx.drawImage(img, dx, dy, w, h)
res()
}
img.src = url
})
}
function Ball() {
this.r = rand(5, 30);
this.x = rand(this.r, screenWidth - this.r);
this.y = rand(this.r, screenHeight - this.r);
this.color = "rgba(" + rand(0, 256) + "," + rand(0, 256) + "," + rand(0, 256) + "," + Math.random() + ")";
this.speedX = rand(1, 10);
this.speedY = rand(1, 10);
}
Ball.prototype.move = function() {
this.x += this.speedX * (rand(0, 2) > 1 ? 1 : -1);
this.y += this.speedY * (rand(0, 2) > 1 ? 1 : -1);
if (this.x >= screenWidth - this.r) {
this.speedX *= -1;
}
if (this.x <= this.r) {
this.speedX *= -1;
}
if (this.y >= screenHeight - this.r) {
this.speedY *= -1;
}
if (this.y <= this.r) {
this.speedY *= -1;
}
}
Ball.prototype.draw = async function() {
ctx.beginPath();
ctx.fillStyle = '#FFF000';
ctx.arc(this.x, this.y, 91, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.save()
ctx.beginPath();
ctx.arc(this.x, this.y - 58 / 2 - 58 / 4, 58 / 2, 0, Math.PI * 2, true);
ctx.clip();
drawImage(ctx, 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603712755852&di=e28f3f8d64303b5a6af1959a9c8ba667&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F30%2F29%2F01300000201438121627296084016.jpg', this.x- 58 / 2 , this.y - 58 - 58 /4);
ctx.restore();
ctx.textAlign = 'center'
ctx.font = '20px yahei';
ctx.fillStyle="#333333"
ctx.fillText('API中文网', this.x, this.y + 58 /10);
ctx.font = '26px yahei';
ctx.fillStyle="#333333"
ctx.fillText('编号:A00001', this.x, this.y + 58 /10 + 30);
}
var balls = [];
for (var i = 0; i < 2; i++) {
var ball = new Ball();
balls.push(ball);
ball.draw();
}
function move() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < balls.length; i++) {
var ball = balls[i];
ball.draw();
ball.move();
}
window.requestAnimationFrame(move);
}
<canvas id="canvasId" width="800" height="600"></canvas>