[英]Animate moving an image in canvas
Im new to using canvas but wonder if i could get some help or advice on where to start with this. 我刚开始使用画布,但想知道我是否可以从此处开始获得一些帮助或建议。 i currently have a circle drawn on canvas and have tried multiple ways i thought might work but cant get my head round it.
我目前在画布上绘制了一个圆圈,并尝试了多种方法,我认为可能可行,但无法解决。 When searching online i can only really find help where the shapes are drawn in canvas itself.
在线搜索时,我只能在画布上绘制形状的地方真正找到帮助。
Here is what i have so far: JSFiddle 这是我到目前为止的内容: JSFiddle
JavaScript: JavaScript:
var one = document.getElementById("canvOne");
var canvOne = one.getContext("2d");
var img = new Image();
img.onload = function(){
canvOne.drawImage(img, 10, 10);
};
img.src = "img/circle.jpg";
function oneStart(){
for(var i = 0; i < 300; i++){
img.style.left = i + 'px';
setTimeout(oneStart, 1000);
}
};
can anyone give me a hand with this please? 有人可以帮我吗?
jsFiddle : http://jsfiddle.net/8eLL7L5L/3/ jsFiddle: http : //jsfiddle.net/8eLL7L5L/3/
javascript javascript
//canvas one
var one = document.getElementById("canvOne");
var canvOne = one.getContext("2d");
var img = new Image();
var animate = false;
var circlePosX = 10;
var circlePosY = 10;
img.onload = function () {
canvOne.drawImage(img, circlePosX, circlePosY);
};
img.src = "http://www.alexvolley.co.uk/other/circle.jpg";
var start = function()
{
animate = true;
}
var stop = function()
{
animate = false;
}
setInterval(function () {
// Only update circle position if animate is true
if (animate) {
circlePosX += 1;
canvOne.fillStyle = "#FFF";
canvOne.fillRect(0, 0, one.width, one.height);
canvOne.drawImage(img, circlePosX, circlePosY);
}
}, 3);
All I have done is created 3 variables and added a few little functions, the circle's XPos and YPos are now stored so we can access them, I have also created a bool
variable animate
which is used to check if we should animate the circle. 我所做的只是创建了3个变量,并添加了一些小函数,现在存储了圆的XPos和YPos,以便我们可以访问它们。我还创建了一个
bool
变量animate
,用于检查是否应为圆设置动画。
The start function simply sets animate
to true start函数只是将
animate
为true
The stop function simple sets animate
to false 停止功能简单地将
animate
为false
the setInterval just keeps running the same code over and over every 3 miliseconds, all this does is clears the canvas and then redraws the circle. setInterval只会每3毫秒重复运行一次相同的代码,所有这些操作就是清除画布,然后重画圆圈。 If we don't clear the canvas you would see multiple circles appear when animate is true.
如果我们不清除画布,则在动画设置为true时会看到多个圆圈。
I hope this helped 希望这对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.