Canvas实现图片切换功能

本文介绍如何利用Canvas实现图片切换功能,作为动态背景的替代方案。通过调整Canvas的代码,可以实现图片的定时切换,避免了频繁修改img标签src属性导致的重绘问题。同时,代码提供了鼠标移入停止切换、移出继续切换以及点击回调函数的功能。相比于img标签,Canvas实现的切换可能需要更多的技巧来添加过渡效果,但能保证更好的性能。
摘要由CSDN通过智能技术生成

这几天研究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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值