gpt4 book ai didi

javascript - 如何将 SVG 图像添加到 javascript html5 Canvas 动画?

转载 作者:行者123 更新时间:2023-11-30 06:16:05 24 4
gpt4 key购买 nike

我目前在 html5 Canvas 中有一个旋转的弹跳球,我希望在球内插入一个 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);

最佳答案

var img = new Image();
img.src = ""; // Put the path to you SVG image here.
img.onload = function() {
ctx.drawImage(img, 0, 0);
}

这应该可行

关于javascript - 如何将 SVG 图像添加到 javascript html5 Canvas 动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56087324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com