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

我目前在html5画布中有一个旋转的弹跳球,并且我希望在球中插入一个SVG图像,该球会随之移动和旋转。研究此代码是我的代码,但不确定这是否正确


var img = new Image();

img.onload = function() {

ctx.drawImage(img, 0, 0);

}

img.src = "";

有人对我如何实现这一目标有任何建议吗?这是我的代码


<canvas id="myCanvas"></canvas>



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

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

var x = canvas.width / 2;

var y = canvas.height / 2;

// SPEED

var dx = 4;

var dy = -4;


var radius = 120;


function 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();


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() {

canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

}


resizeCanvas();


x = canvas.width / 2;

y = canvas.height / 2;


setInterval(draw, 10);


POPMUISE
浏览 312回答 2
2回答

慕哥9229398

var img = new Image();img.src = ""; // Put the path to you SVG image here.img.onload = function() {&nbsp; &nbsp; ctx.drawImage(img, 0, 0);}这应该工作
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript