gpt4 book ai didi

javascript - Canvas 振荡图像

转载 作者:行者123 更新时间:2023-11-28 01:26:35 25 4
gpt4 key购买 nike

我正在尝试让图像振荡。但我有一些问题。我正在使用本教程http://www.html5canvastutorials.com/advanced/html5-canvas-oscillation-animation/

我尝试更改教程的第 55-61 行来加载图像 src。但它没有显示任何内容。

有什么建议吗?

<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();

function drawRectangle(myRectangle, context) {
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = '#8ED6FF';
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = 'black';
context.stroke();
}
function animate(myRectangle, canvas, context, startTime) {
// update
var time = (new Date()).getTime() - startTime;
var amplitude = 150;

// in ms
var period = 2000;
var centerX = canvas.width / 2 - myRectangle.width / 2;
var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;
myRectangle.x = nextX;

// clear
context.clearRect(0, 0, canvas.width, canvas.height);

// draw
drawRectangle(myRectangle, context);

// request new frame
requestAnimFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

var myRectangle = new Image();
myRectangle.src = "http://www.skilledsoldiers.com/e107_plugins/aacgc_gamelist/icons/dota2_icon.png";
myRectangle.onload = function()
};

drawRectangle(myRectangle, context);

// wait one second before starting animation
setTimeout(function() {
var startTime = (new Date()).getTime();
animate(myRectangle, canvas, context, startTime);
}, 1000);
</script>

最佳答案

您需要使用context.drawImage,而不是尝试用图像绘制矩形。

function drawImage(myRectangle, context) {
context.drawImage(myRectangle.img, myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
}

看到这个 fiddle :http://jsfiddle.net/fb4vS/

关于javascript - Canvas 振荡图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22616304/

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