这几天研究canvas制作动态背景的时候,发现这个东西稍微改改就变成图片切换的功能了,可以代替动态修改img标签的src属性,实现图片定时切换功能。先奉上代码:
function switchPic(containerId, pics, {
speed = 1000,
width = 100,
height = 100,
callback = function(pic) {}
} = {}) {
//判断
if (!containerId || !pics)
throw new Error ("TypeError: switchPic-->
containerId or pics is undefined!");
if(typeof containerId !== "string" ||
{}.toString.call(pics) !== "[object Array]" )
throw new Error ("TypeError: switchPic-->
containerId is not string or pics is not array!");
//制作canvas
let canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.style.cursor = "pointer";
//放入canvas
document.querySelector("#" + containerId).appendChild(canvas);
ctx = canvas.getContext("2d");
let img = new Image(