1. 通過(guò)canvas自帶的畫(huà)布方法進(jìn)行翻轉(zhuǎn)
var img = new Image(); //這個(gè)就是 img標(biāo)簽的dom對(duì)象
img.src = './sy.png';
img.onload = function () {
//圖片加載完成后,執(zhí)行此方法
ctx.drawImage(img, posx, posy, 210, 80);
};
play.addEventListener('click', function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);//清除畫(huà)布
//位移來(lái)做鏡像翻轉(zhuǎn)
ctx.translate(210+ posx * 2, 0);
ctx.scale(-1, 1); //左右鏡像翻轉(zhuǎn)
//ctx.translate(0, 160 + posy * 2);
//ctx.scale(1, -1); //上下鏡像翻轉(zhuǎn)
ctx.drawImage(img, 0, 0, 210, 80);
});
2.像素點(diǎn)的鏡像翻轉(zhuǎn)方法
//豎向像素反轉(zhuǎn)
function imageDataVRevert(sourceData, newData) {
for (var i = 0, h = sourceData.height; i < h; i++) {
for (var j = 0, w = sourceData.width; j < w; j++) {
newData.data[i * w * 4 + j * 4 + 0] =
sourceData.data[(h - i) * w * 4 + j * 4 + 0];
newData.data[i * w * 4 + j * 4 + 1] =
sourceData.data[(h - i) * w * 4 + j * 4 + 1];
newData.data[i * w * 4 + j * 4 + 2] =
sourceData.data[(h - i) * w * 4 + j * 4 + 2];
newData.data[i * w * 4 + j * 4 + 3] =
sourceData.data[(h - i) * w * 4 + j * 4 + 3];
}
}
return newData;
}
//橫向像素反轉(zhuǎn)
function imageDataHRevert(sourceData, newData) {
for (var i = 0, h = sourceData.height; i < h; i++) {
for (j = 0, w = sourceData.width; j < w; j++) {
newData.data[i * w * 4 + j * 4 + 0] =
sourceData.data[i * w * 4 + (w - j) * 4 + 0];
newData.data[i * w * 4 + j * 4 + 1] =
sourceData.data[i * w * 4 + (w - j) * 4 + 1];
newData.data[i * w * 4 + j * 4 + 2] =
sourceData.data[i * w * 4 + (w - j) * 4 + 2];
newData.data[i * w * 4 + j * 4 + 3] =
sourceData.data[i * w * 4 + (w - j) * 4 + 3];
}
}
return newData;
}
``
var img = new Image(); //這個(gè)就是 img標(biāo)簽的dom對(duì)象
img.src = './sy.png';
img.onload = function () {
//圖片加載完成后,執(zhí)行此方法
ctx.drawImage(img, 0, 0, 210, 80);
};
//像素點(diǎn)操作
var imgData = ctx.getImageData(0, 0, 210, 80);
var newImgData = ctx.getImageData(0, 0, 210, 80);
// var newImgData = ctx.getImageData(0, 0, w, h);
ctx.putImageData(imageDataVRevert(newImgData, imgData), 0, 0); //上下翻轉(zhuǎn)
// ctx.putImageData(imageDataHRevert(newImgData, imgData), 0, 0);//左右翻轉(zhuǎn)~~~~
到此這篇關(guān)于canvas實(shí)現(xiàn)圖片鏡像翻轉(zhuǎn)的2種方式的文章就介紹到這了,更多相關(guān)canvas圖片鏡像翻轉(zhuǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!