我已经开始学习HTML5中的Canvas,并且我有一个问题。重复的移动模式?
我想重复创建一个可移动的模式。 (类似于CSS中背景位置和背景重复。)
我该怎么做?
我需要这个为我的项目创建一个动画背景。
我已经开始学习HTML5中的Canvas,并且我有一个问题。重复的移动模式?
我想重复创建一个可移动的模式。 (类似于CSS中背景位置和背景重复。)
我该怎么做?
我需要这个为我的项目创建一个动画背景。
即使世界一些方法来实现这一目标,你可以使用putImageData
但你会遭受一些性能的损失,最好方法是使用drawImage
。另请注意,第二种方法的代码可以使其从左到右,或从右到左。
http://www.somethinghitme.com/projects/bgscroll/scrolldrawimage.html
var ctx = document.getElementById("canvas").getContext("2d"),
canvasTemp = document.createElement("canvas"),
scrollImg = new Image(),
tempContext = canvasTemp.getContext("2d"),
imgWidth = 0,
imgHeight =0,
imageData = {},
canvasWidth = 600,
canvasHeight = 240,
scrollVal = 0,
speed =2;
scrollImg.src = "citybg.png";
scrollImg.onload = loadImage;
function loadImage(){
imgWidth = scrollImg.width,
imgHeight = scrollImg.height;
canvasTemp.width = imgWidth;
canvasTemp.height = imgHeight;
render();
}
function render(){
ctx.clearRect(0,0,canvasWidth,canvasHeight);
if(scrollVal >= canvasWidth){
scrollVal = 0;
}
scrollVal+=speed;
ctx.drawImage(scrollImg,canvasWidth-scrollVal,0,scrollVal,imgHeight, 0, 0, scrollVal,imgHeight);
ctx.drawImage(scrollImg,scrollVal,0,imgWidth, imgHeight);
// To go the other way instead
ctx.drawImage(scrollImg,-scrollVal,0,imgWidth, imgHeight);
ctx.drawImage(scrollImg,canvasWidth-scrollVal,0,imgWidth, imgHeight);
setTimeout(function(){render();},10);
}
你可以做这样的事情。 首先使用setInterval()创建一个用于移动和触发该函数的函数setInterval方法是用于计时事件的窗口对象。它会在指定的毫秒数内反复执行函数或表达式。
你可以参考post.I创建的示例蛇游戏使用html5画布和音频。 http://www.arungudelli.com/2012/10/html5-canvas-example-snake-game.html
您可以使用CSS3为背景图案设置动画效果。您可以在动画上叠加其他画布元素,并通过切换类来控制JavaScript的动画。
body {
background:url('http://pattern8.com/images/pattern-thumbs/pattern8-pattern-61c.png');
}
body.scrollbg {
-webkit-animation: scrollbg 6s cubic-bezier(.4,0,.2,1) infinite;
...(moz,ms,o vendor prefixes)...
animation: scrollbg 6s cubic-bezier(.4,0,.2,1) infinite;
}
@-webkit-keyframes scrollbg {
0% { background-position: left top, left top; }
25% { background-position: right top, left bottom; }
50% { background-position: right bottom, right bottom; }
75% { background-position: left bottom, right top; }
100% { background-position: left top, left top; }
}
也参见:
support is widely available (sans IE < 10)
IE浏览器支持,你可以使用类似这样canvas animation template