我正在尝试通过不断地交换2个图像并在缓冲画布上将它们用作fillStyle
(模式)来创建如上所述的横幅。我们的想法是在image2后面使用image1跟踪,其中像素的宽度与画布的宽度一样多,并在绘制到我页面上可见的画布上之前,在缓冲画布上同时更新它们的位置。当然,当一个图像移出边框时,会设置该图像的新源,而其x位置设置为负像画布宽度的负像素。
我用于x_incr的值可能看起来很神秘,但它们只是暂时的,任意的值,这使得平滑,增加的速度,因为我还没有找到更好的方法来模拟这种效果。
我使用了1张图片,但是现在我添加了另一张图片,我的画布在脚本运行时始终是黑色的。为什么会这样?我是不是错了?使用CSS3转换可以更好地获取/维护它吗?
我对我在这里使用的所有语言都很陌生,但我试图遵循我所知道的标准。
如果以下代码的部分内容与我的问题有关,请告诉我。
提前致谢!
JavaScript的:
var pattern1;
var pattern2;
var x1 = 0.1;
var x2 = 0.1;
var x1_incr = 0.1;
var x2_incr = 0.1;
var canvas = null;
var context = null;
var bufferCanvas = null;
var bufferCanvasCtx = null;
var img1 = new Image();
var img2 = new Image();
var currentImg = 0;
var imgArray = [
"images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg"
];
function Init () {
canvas = document.getElementById('Canvas1');
context = canvas.getContext("2d");
bufferCanvas = document.createElement("canvas");
bufferCanvasCtx = bufferCanvas.getContext("2d");
bufferCanvasCtx.canvas.width = context.canvas.width;
bufferCanvasCtx.canvas.height = context.canvas.height;
loadPattern(img1, pattern1);
loadPattern(img2, pattern2);
SwitchImage(img1);
Draw();
setInterval(Animate, 10);
}
function loadPattern(image, pattern) {
image.onload = function () {
pattern = bufferCanvasCtx.createPattern(image, "no-repeat");
};
}
function SwitchImage(obj) {
obj.setAttribute('src', imgArray[currentImg++]);
if (currentImg >= imgArray.length) {
currentImg = 0;
}
}
function Animate () {
Update(img1, x1, x1_incr);
Update(img2, x2, x2_incr);
Draw();
}
function Update (image, x, x_incr) {
x_incr += 0.1;
x += x_incr;
if (x > context.canvas.width) {
SwitchImage(image);
x = -context.canvas.width;
x_incr = 0.1;
}
}
function Draw() {
context.save();
if (x1 < x2) {
bufferCanvasCtx.fillStyle = pattern1;
bufferCanvasCtx.fillRect(x1, 0, context.canvas.width, context.canvas.height);
bufferCanvasCtx.fillStyle = pattern2;
bufferCanvasCtx.fillRect(x2, 0, context.canvas.width, context.canvas.height);
}
else {
bufferCanvasCtx.fillStyle = pattern2;
bufferCanvasCtx.fillRect(x2, 0, context.canvas.width, context.canvas.height);
bufferCanvasCtx.fillStyle = pattern1;
bufferCanvasCtx.fillRect(x1, 0, context.canvas.width, context.canvas.height);
}
context.drawImage(bufferCanvas, 0, 0, context.canvas.width, context.canvas.height);
context.restore();
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<LINK href="mypage.css" rel="stylesheet" type="text/css">
</head>
<body onload="Init()">
<div class="container">
<canvas id="Canvas1" class="slideshow">Your browser does not support canvas.</canvas>
</div>
<script src="mypage.js">
</script>
</body>
</html>
CSS:
.container {
margin: auto;
width: 1024px;
}
.slideshow {
background-color: lightGray;
height: 90px;
width: 728px;
margin: 0 auto 0 auto;
display: block;
}