有canvas一个从球壁反弹的动画。如何让圣诞老人在屏幕上走动而不是球(img图片),当它撞到墙上时,它会变成蓝色背景的圣诞树,当与墙壁发生新的碰撞时会循环变成圣诞老人白色背景?
传递图像对象
ctx.drawImage(santa, 120, 340);
怎么让他动起来?
还有一个额外的问题:需要做什么才能在您单击带有(圣诞老人/圣诞树)的图片时,动画停止并出现“新家庭和圣诞节快乐”字样
var can = document.querySelector("canvas");
var ctx = can.getContext("2d");
var canvasWidth = can.width;
var canvasHeight = can.height;
var radius = 30;
var pX = 60;
var pY = 50;
var vX = 3;
var vY = 3;
var santa = document.querySelector(".santa");
var tree = document.querySelector(".tree");
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.drawImage(santa, 120, 340);
ctx.drawImage(tree, 120, 340);
ctx.fillStyle = "red";
ctx.arc(pX, pY, radius, 0, Math.PI * 2, false);
ctx.fill();
ctx.closePath();
}
function animate() {
if (pY >= canvasHeight - radius || pY <= radius) {
vY = -vY;
}
if (pX > canvasWidth - radius || pX < radius) {
vX *= -1;
}
pX += vX;
pY += vY;
draw();
requestAnimationFrame(animate);
}
animate();
<canvas style="border-style: solid;" width="240px" height="400px"></canvas>
<img class="santa" src="https://i.pinimg.com/originals/0e/f6/c1/0ef6c11df3a2fb3ce04de96cf620ac65.jpg" width="80">
<img class="tree" src="https://img1.labirint.ru/rcimg/e20fb45c1ff31a0789cab36beb9cda1f/960x540/books73/726265/ph_01.jpg?1574439967" width="80">
ctx.drawImage(santa, 120, 340);- 图片尺寸未标明,均按原始比例绘制。而120和340是图片左上角的坐标。它们超出了画布,这就是它们不显示的原因。一定是
ctx.drawImage(santa, 120, 340, ширина_картинки, высота);周围: