我正在尝试使用JavaScript和HTML Canvas创建动画故障效果。我设法将图像绘制到画布上,并希望编写一个单独的函数,以后将该图像拆分为几行,以便可以分别对其进行动画处理。
我调用函数创建画布...
var logo_text = "logo_text.png";
drawOnCanvas(logo_text, mc_logo_text, 0, 0, 245, 60);
这就是函数的样子……
function drawOnCanvas(image, divID, posX, posY, wid, hei) {
//////////// CREATE CANVAS /////////////
var canvas = document.createElement("CANVAS"),
ctx = canvas.getContext("2d");
canvas.width = wid;
canvas.height = hei;
canvas.id = divID.id+"_canvas";
divID.appendChild(canvas);
//////////// DRAW IMAGE /////////////
var img = new Image();
img.src = image;
img.onload = function () {
ctx.drawImage(img, posX, posY, wid, hei);
} }
此功能工作正常,并在需要的位置绘制图像。我只是想不出将它分成几行的最佳方法。
答案 0 :(得分:0)
尝试一下!
您只需要编辑_config
数组的每个对象中的设置。
drawOnCanvas()
将执行与_config
中的对象编号相同的次数。
顺便说一句,脚本需要在DIV
s下方导入,以便document.getElementById
可以找到它们。
<body>
<div id="mc_logo_text1"></div>
<div id="mc_logo_text2"></div>
<div id="mc_logo_text3"></div>
<script>
// Simply edit all settings here
var _config = [
{
src: 'logo_text.png',
domDiv: 'mc_logo_text1',
position: {x: 0, y: 0},
size: {w: 245, h: 60}
},
{
src: 'logo_text.png',
domDiv: 'mc_logo_text2',
position: {x: 0, y: 0},
size: {w: 245, h: 60}
},
{
src: 'logo_text.png',
domDiv: 'mc_logo_text3',
position: {x: 0, y: 0},
size: {w: 245, h: 60}
}
]
/////// No Need to modify ////////
var drawOnCanvas = function(config) {
var canvas = document.createElement("CANVAS");
var ctx = canvas.getContext("2d");
//Define which DIV to include new Canvas
var domTaget = document.getElementById(config.domDiv);
// Create Canvas & give new ID name
function _canvasInit() {
canvas.width = config.size.w;
canvas.height = config.size.h;
canvas.id = domTaget.id + "_canvas";
domTaget.appendChild(canvas);
}
// draw images into canvas
function _drawImgs() {
var img = new Image();
img.src = config.src;
img.onload = function() {
ctx.drawImage(img, config.position.x, config.position.y, canvas.width, canvas.height);
}
}
// Do all functions
_canvasInit();
_drawImgs();
}
// Each object in _config array do drawOnCanvas function,
for (var i = 0; i < _config.length; i = i + 1) {
drawOnCanvas(_config[i]);
}
/////// No Need to modify ////////
</script>
</body>