要通過canvas實現對圖片沿x軸或者顏色y軸實現翻轉,我們可以通過canvas2d的接口進行實現。
使用到的api:
使用getContext來獲取canvas2d對象
使用 canvas2d對象的scale方法進行翻轉
由於翻轉的xy軸使用的是原點,也就是canvas的左上角的位置的軸,所以,我們還需要使用到translate方法,來移動將翻轉後的圖片移動到canvas的顯示區域
邏輯說完了,那麼上一下簡短的翻轉代碼:
- 沿x軸翻轉代碼:
//垂直翻轉
ctx.scale(1, -1);
ctx.translate(0, -canvas.height);
- 沿y軸翻轉代碼:
//水平翻轉
ctx.scale(-1, 1);
ctx.translate(-canvas.width, 0);
以上就是沿x軸和y軸翻轉的代碼,下面再奉上一個demo的代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
var preName = './textures/build/admin_edit/1574131406/a1574212341_p0_';
var img = new Image();
img.src = preName+ 'x.jpg';
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.height = img.height;
canvas.width = img.width;
//水平翻轉
ctx.scale(-1, 1);
ctx.translate(-img.width, 0);
//垂直翻轉
ctx.scale(1, -1);
ctx.translate(0, -img.height);
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
canvas.style.cssText = 'position:fixed; left:0; top:0;';
document.body.appendChild(canvas);
}
</script>
</html>