如何在html5中插入动画,如何将SVG图像添加到javascript html5 canvas动画中?

一种方法是将图像隐藏在HTML中。在这种情况下,图像是作为数据uri的svg并具有id="apple"和,您可以说:

var img = apple;

要在球内绘制图像,您需要使用球的中心,例如:

ctx.drawImage(img, x-img.width/2,y-img.height/2)

另外,setInterval我没有使用requestAnimationFrame,而是在调整大小时图像没有脱离屏幕。希望您会发现我的回答有用。

var canvas = document.getElementById("myCanvas");

var ctx = canvas.getContext("2d");

var x = canvas.width / 2;

var y = canvas.height / 2;

var rid = null;// request animation id

// SPEED

var dx = 4;

var dy = -4;

var radius = 120;

var img = apple;// the image is the one with the id="apple"

function draw() {

rid = window.requestAnimationFrame(draw);

ctx.clearRect(0, 0, canvas.width, canvas.height);

ctx.beginPath();

ctx.arc(x, y, radius, 0, Math.PI * 2);

ctx.fillStyle = "#9370DB";

ctx.fill();

ctx.closePath();

//draw the image in the center of the ball

ctx.drawImage(img, x-img.width/2,y-img.height/2)

if (x + dx > canvas.width - radius) {

dx = -dx;

}

if (x + dx < radius) {

dx = -dx;

}

if (y + dy > canvas.height - radius) {

dy = -dy;

}

if (y + dy < radius) {

dy = -dy;

}

x += dx;

y += dy;

}

window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {

//stop the animation

if(rid){window.cancelAnimationFrame(rid); rid= null;}

//get the size of the canvas

canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

x = canvas.width / 2;

y = canvas.height / 2;

//restart the animation

draw()

}

window.setTimeout(function() {

resizeCanvas();

window.addEventListener('resize', resizeCanvas, false);

}, 15);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值